argparse supports nargs parameter, which tells you how many parameters it eats. When nargs="+" it accepts one or more parameters, so you can pass -b 1 2 3 4 and it will be assigned as a list to b argument

# args.py
import argparse

p = argparse.ArgumentParser()

# accept two lists of arguments
# like -a 1 2 3 4 -b 1 2 3
p.add_argument('-a', nargs="+", type=int)
p.add_argument('-b', nargs="+", type=int)
args = p.parse_args()

# check if input is valid
set_a = set(args.a)
set_b = set(args.b)

# check if "a" is in proper range.
if len(set_a - set(range(1, 51))) > 0: # can use also min(a)>=1 and max(a)<=50
    raise Exception("set a not in range [1,50]")

# check if "b" is in "a"
if len(set_b - set_a) > 0:
    raise Exception("set b not entirely in set a")

# you could even skip len(...) and leave just operations on sets
# ...

So you can run:

$ python arg.py  -a 1 2 3 4 -b 2 20
Exception: set b not entirely in set a

$ python arg.py  -a 1 2 3 4 60 -b 2
Exception: set a not in range [1,50]

And this is valid:

$ python arg.py  -a 1 2 3 4 -b 2 3
Answer from Jakub M. on Stack Overflow
Top answer
1 of 6
90

argparse supports nargs parameter, which tells you how many parameters it eats. When nargs="+" it accepts one or more parameters, so you can pass -b 1 2 3 4 and it will be assigned as a list to b argument

# args.py
import argparse

p = argparse.ArgumentParser()

# accept two lists of arguments
# like -a 1 2 3 4 -b 1 2 3
p.add_argument('-a', nargs="+", type=int)
p.add_argument('-b', nargs="+", type=int)
args = p.parse_args()

# check if input is valid
set_a = set(args.a)
set_b = set(args.b)

# check if "a" is in proper range.
if len(set_a - set(range(1, 51))) > 0: # can use also min(a)>=1 and max(a)<=50
    raise Exception("set a not in range [1,50]")

# check if "b" is in "a"
if len(set_b - set_a) > 0:
    raise Exception("set b not entirely in set a")

# you could even skip len(...) and leave just operations on sets
# ...

So you can run:

$ python arg.py  -a 1 2 3 4 -b 2 20
Exception: set b not entirely in set a

$ python arg.py  -a 1 2 3 4 60 -b 2
Exception: set a not in range [1,50]

And this is valid:

$ python arg.py  -a 1 2 3 4 -b 2 3
2 of 6
16

You can pass them as strings than convert to lists. You can use argparse or optparse.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--l1', type=str)
parser.add_argument('--l2', type=str)
args = parser.parse_args()
l1_list = args.l1.split(',') # ['1','2','3','4']

Example: python prog.py --l1=1,2,3,4

Also,as a line you can pass something like this 1-50 and then split on '-' and construct range. Something like this:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--l1', type=str, help="two numbers separated by a hyphen")
parser.add_argument('--l2', type=str)
args = parser.parse_args()
l1_list_range = xrange(*args.l1.split('-')) # xrange(1,50)
for i in l1_list_range:
    print i

Example: python prog.py --l1=1-50

Logic I think you can write yourself. :)

🌐
Python
docs.python.org › 3 › library › argparse.html
argparse — Parser for command-line options, arguments and subcommands
The nargs keyword argument associates a different number of command-line arguments with a single action. See also Specifying ambiguous arguments. The supported values are: N (an integer). N arguments from the command line will be gathered together into a list. For example: >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo', nargs=2) >>> parser.add_argument('bar', nargs=1) >>> parser.parse_args('c --foo a b'.split()) Namespace(bar=['c'], foo=['a', 'b'])
Discussions

python argh/argparse: How can I pass a list as a command-line argument? - Stack Overflow
I'm trying to pass a list of arguments to a python script using the argh library. Something that can take inputs like these: ./my_script.py my-func --argA blah --argB 1 2 3 4 ./my_script.py my-fu... More on stackoverflow.com
🌐 stackoverflow.com
python - How can I pass a list as a command-line argument with argparse? - Stack Overflow
If only parsing integers this is fine. 2018-01-09T20:59:48.597Z+00:00 ... I think the most elegant solution is to pass a lambda function to "type", as mentioned by Chepner. In addition to this, if you do not know beforehand what the delimiter of your list will be, you can also pass multiple delimiters to re.split: # python3 test.py -l "abc xyz, 123" import re import argparse ... More on stackoverflow.com
🌐 stackoverflow.com
subprocess - Python argparse storing arguments as lists rather than ints. Confusing or correct? - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Closed 4 years ago. I am using two test scripts to teach myself how to use argparse and subprocess libraries in Python. More on stackoverflow.com
🌐 stackoverflow.com
argparse choices allow multiple values
specify nargs. '+' will collect 1+ arguments. https://repl.it/repls/AjarTepidMemwatch More on reddit.com
🌐 r/learnpython
1
1
February 25, 2020
🌐
Flexiple
flexiple.com › python › python-argparse-list
Python argparse - Flexiple
March 27, 2024 - Python argparse is a powerful module that simplifies the process of parsing command-line arguments in Python scripts. In this comprehensive blog, we'll explore the ins and outs of using argparse to handle lists of values as command-line arguments.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-pass-a-list-as-a-command-line-argument-with-argparse
How to pass a list as a command-line argument with argparse? - GeeksforGeeks
July 23, 2025 - In this example, the list_of_ints function takes a string as input and returns a list of Python integers. The type parameter of add_argument is set to list_of_ints, so when parse_args is called, the string value of --int-list is converted into ...
🌐
Bobby Hadz
bobbyhadz.com › blog › python-argparse-pass-multiple-arguments-as-list
Python argparse: Pass a List as command-line argument | bobbyhadz
April 13, 2024 - If you want to get the result as a list of integers, use a list comprehension. main.py · Copied!import argparse parser = argparse.ArgumentParser( description='A sample Argument Parser.'
🌐
Kodeclik
kodeclik.com › python-argumentparser-list
Passing a list as a command-line argument to Python
September 24, 2024 - The argparse module provides a powerful way to parse command-line arguments. In this blogpost, we will explore the ArgumentParser class, focusing specifically on using it to handle lists of arguments. Let's start by understanding the basic usage of the ArgumentParser class without considering list arguments. We will create a simple Python script that takes two integers ...
🌐
Oak-Tree Technologies
oak-tree.tech › blog › snippet-argparse-csv
Python Snippets: Splitting CSV lists in argparse
Consider the example below (stolen from the argparse documentation), which takes a list of integers and produces either the sum or the max.
Find elsewhere
🌐
Python documentation
docs.python.org › 3 › howto › argparse.html
Argparse Tutorial — Python 3.14.4 documentation
Remember that by default, if an optional argument isn’t specified, it gets the None value, and that cannot be compared to an int value (hence the TypeError exception). ... You can go quite far just with what we’ve learned so far, and we have only scratched the surface. The argparse module is very powerful, and we’ll explore a bit more of it before we end this tutorial.
🌐
University of New Brunswick
cs.unb.ca › ~bremner › teaching › cs2613 › books › python3-doc › library › argparse.html
argparse — Parser for command-line options, arguments and sub-commands — Python 3.9.2 documentation
Later, calling parse_args() will return an object with two attributes, integers and accumulate. The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.
🌐
CSDN
devpress.csdn.net › python › 62fd47df7e66823466191d00.html
How can I pass a list as a command-line argument with argparse?_python_Mangs-Python
August 18, 2022 - $ python arg.py --list-type "1234 2345 3456 4567" ['1', '2', '3', '4', ' ', '2', '3', '4', '5', ' ', '3', '4', '5', '6', ' ', '4', '5', '6', '7'] $ python arg.py --list-type-nargs 1234 2345 3456 4567 [['1', '2', '3', '4'], ['2', '3', '4', '5'], ['3', '4', '5', '6'], ['4', '5', '6', '7']] $ python arg.py --nargs 1234 2345 3456 4567 ['1234', '2345', '3456', '4567'] $ python arg.py --nargs-int-type 1234 2345 3456 4567 [1234, 2345, 3456, 4567] $ # Negative numbers are handled perfectly fine out of the box. $ python arg.py --nargs-int-type -1234 2345 -3456 4567 [-1234, 2345, -3456, 4567] $ python a
Top answer
1 of 13
1688

SHORT ANSWER

Use the nargs option or the 'append' setting of the action option (depending on how you want the user interface to behave).

nargs

parser.add_argument('-l','--list', nargs='+', help='<Required> Set flag', required=True)
# Use like:
# python arg.py -l 1234 2345 3456 4567

nargs='+' takes 1 or more arguments, nargs='*' takes zero or more.

append

parser.add_argument('-l','--list', action='append', help='<Required> Set flag', required=True)
# Use like:
# python arg.py -l 1234 -l 2345 -l 3456 -l 4567

With append you provide the option multiple times to build up the list.

Don't use type=list!!! - There is probably no situation where you would want to use type=list with argparse. Ever.


LONG ANSWER

Let's take a look in more detail at some of the different ways one might try to do this, and the end result.

import argparse

parser = argparse.ArgumentParser()

# By default it will fail with multiple arguments.
parser.add_argument('--default')

# Telling the type to be a list will also fail for multiple arguments,
# but give incorrect results for a single argument.
parser.add_argument('--list-type', type=list)

# This will allow you to provide multiple arguments, but you will get
# a list of lists which is not desired.
parser.add_argument('--list-type-nargs', type=list, nargs='+')

# This is the correct way to handle accepting multiple arguments.
# '+' == 1 or more.
# '*' == 0 or more.
# '?' == 0 or 1.
# An int is an explicit number of arguments to accept.
parser.add_argument('--nargs', nargs='+')

# To make the input integers
parser.add_argument('--nargs-int-type', nargs='+', type=int)

# An alternate way to accept multiple inputs, but you must
# provide the flag once per input. Of course, you can use
# type=int here if you want.
parser.add_argument('--append-action', action='append')

# To show the results of the given option to screen.
for _, value in parser.parse_args()._get_kwargs():
    if value is not None:
        print(value)

Here is the output you can expect:

$ python arg.py --default 1234 2345 3456 4567
...
arg.py: error: unrecognized arguments: 2345 3456 4567

$ python arg.py --list-type 1234 2345 3456 4567
...
arg.py: error: unrecognized arguments: 2345 3456 4567

$ # Quotes won't help here... 
$ python arg.py --list-type "1234 2345 3456 4567"
['1', '2', '3', '4', ' ', '2', '3', '4', '5', ' ', '3', '4', '5', '6', ' ', '4', '5', '6', '7']

$ python arg.py --list-type-nargs 1234 2345 3456 4567
[['1', '2', '3', '4'], ['2', '3', '4', '5'], ['3', '4', '5', '6'], ['4', '5', '6', '7']]

$ python arg.py --nargs 1234 2345 3456 4567
['1234', '2345', '3456', '4567']

$ python arg.py --nargs-int-type 1234 2345 3456 4567
[1234, 2345, 3456, 4567]

$ # Negative numbers are handled perfectly fine out of the box.
$ python arg.py --nargs-int-type -1234 2345 -3456 4567
[-1234, 2345, -3456, 4567]

$ python arg.py --append-action 1234 --append-action 2345 --append-action 3456 --append-action 4567
['1234', '2345', '3456', '4567']

Takeaways:

  • Use nargs or action='append'
    • nargs can be more straightforward from a user perspective, but it can be unintuitive if there are positional arguments because argparse can't tell what should be a positional argument and what belongs to the nargs; if you have positional arguments then action='append' may end up being a better choice.
    • The above is only true if nargs is given '*', '+', or '?'. If you provide an integer number (such as 4) then there will be no problem mixing options with nargs and positional arguments because argparse will know exactly how many values to expect for the option.
  • Don't use quotes on the command line1
  • Don't use type=list, as it will return a list of lists
    • This happens because under the hood argparse uses the value of type to coerce each individual given argument you your chosen type, not the aggregate of all arguments.
    • You can use type=int (or whatever) to get a list of ints (or whatever)

1: I don't mean in general.. I mean using quotes to pass a list to argparse is not what you want.

2 of 13
157

I prefer passing a delimited string which I parse later in the script. The reasons for this are; the list can be of any type int or str, and sometimes using nargs I run into problems if there are multiple optional arguments and positional arguments.

parser = ArgumentParser()
parser.add_argument('-l', '--list', help='delimited list input', type=str)
args = parser.parse_args()
my_list = [int(item) for item in args.list.split(',')]

Then,

python test.py -l "265340,268738,270774,270817" [other arguments]

or,

python test.py -l 265340,268738,270774,270817 [other arguments]

will work fine. The delimiter can be a space, too, which would though enforce quotes around the argument value like in the example in the question.

Or you can use a lambda type as suggested in the comments by Chepner:

parser.add_argument('-l', '--list', help='delimited list input', 
    type=lambda s: [int(item) for item in s.split(',')])
🌐
Educative
educative.io › answers › what-is-addargument-in-the-python-argparse-module
What is add_argument in the Python argparse module?
When we call the parse_args method, it returns an object with two attributes, integers and accumulate. The integers attribute is a list of ints, and the accumulate attribute is the function that is executed on the list.
🌐
Medium
injaelee.medium.com › handy-code-argparse-python-argument-parser-9df93456a04f
Handy Code: ‘argparse’ — Python Argument Parser | by Injae Lee | Medium
March 5, 2023 - As a Python software developer, I want to learn about the various uses of “argparse” in Python · # tested on Python 3.9.10 import argparse import datetime def parse_arguments() -> argparse.Namespace: arg_parser = argparse.ArgumentParser() # use an integer as the argument value # arg_parser.add_argument( "-a", "--atasks", help = "specify the number of async tasks", type = int, default = 3, ) # limit the argument values to a specific set # in this case 3 modes are provided # arg_parser.add_argument( "-m", "--mode", choices = ["mode1", "mode2", "mode3"], help = "specify the runmode", type = str, default = "mode1", ) # use an integer and constraint the values to a range # of values # arg_parser.add_argument( "-t", "--throttlewait", help = "specify the number of seconds to wait for throttling", type = int, choices = range(2, 10), # you know how to use 'range', right?
🌐
Galaxy
training.galaxyproject.org › training-material › topics › data-science › tutorials › python-argparse › tutorial.html
Hands-on: Python - Argparse / Python - Argparse / Foundations of Data Science
January 24, 2023 - args.integer # A single integer args.many_integers # A list of ints args.sum # A boolean, True or False. Let’s go back to our script, and replace sys with argparse.
🌐
Clay-Technology World
clay-atlas.com › home › [python] how to "argparse" package to pass "list" data to program via terminal
[Python] How to "argparse" package to Pass "List" Data To Program Via Terminal - Clay-Technology World
August 13, 2021 - Basically, just add a parameter like nargs="+" to add_argument(). But still be careful, set the type of the specified data type to List. ... # coding: utf-8 import argparse # Argument parser = argparse.ArgumentParser() parser.add_argument('...
🌐
Python
bugs.python.org › issue34803
Issue 34803: argparse int type does not accept scientific notation - Python tracker
September 25, 2018 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/78984