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.

Answer from SethMMorton on Stack Overflow
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(',')])
🌐
Python
docs.python.org › 3 › library › argparse.html
argparse — Parser for command-line options, arguments and subcommands
Source code: Lib/argparse.py Tutorial: This page contains the API reference information. For a more gentle introduction to Python command-line parsing, have a look at the argparse tutorial. The arg...
Discussions

How to pass and parse a list of strings from command line with argparse.ArgumentParser in Python? - Stack Overflow
I want to pass a list of names into my program written in Python from console. For instance, I would like to use a way similar to this (I know it shouldn't work because of bash): $ python myprog.p... More on stackoverflow.com
🌐 stackoverflow.com
--advanced-help for argparse - Ideas - Discussions on Python.org
When using argparse, users can get a list of parameters by passing the -h or --help parameter. Sometimes, it’d be nice to hide debug parameters or rare usage parameters from the list of help and only show these w/ an --advanced-help parameter. More on discuss.python.org
🌐 discuss.python.org
0
October 25, 2022
How do I pass my own arguments to argparse without using the command line?
If you're just talking about while you're developing/debugging, it's pretty simple. Just create a launch.json, Run and Debug tab on the left > create a launch.json file. The JSON can look something like this: { "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal", "args": ["-i", "input.txt", "-o", "output.txt"] } ] } main.py import sys print(sys.argv) Hit F5 (or start debugging) Output ['c:\\main.py', '-i', 'input.txt', '-o', 'output.txt'] Edit: To be clear, sys.argv was just to illustrate the point, because it's simpler and faster, but it'll work with argparse as well. More on reddit.com
🌐 r/learnpython
17
3
February 9, 2024
How to use Argparse properly in the main function?
It's not typical to use double-dash arguments to have completely different code paths. Those are usually used to set config parameters, like, say, the directory to read from, or a file to write to, or a boolean arg that says whether to do it this way or that way If you want to have completely different paths of execution, you usually use sub-commands. On the command line this would look like, say, "git status" vs "git commit" vs "git push" etc, i.e. status, commit and push are subcommands that have completely different arg handling. You use argparse's "add_subparsers" function to do this - the docs have many examples Most of the stuff you add with double-dash arguments will hust be present on the args object after parsing and you'll use to set some defaults, maybe handle one way vs another, etc. More on reddit.com
🌐 r/learnpython
16
10
March 11, 2024
🌐
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 a list of integers. ... # import module import argparse # Define a custom argument type for a list of integers def list_of_ints(arg): return list(map(int, arg.split(','))) # Create an ArgumentParser object parser = argparse.ArgumentParser() # Add an argument for the list of integers parser.add_argument('--int-list', type=list_of_ints) # Parse the command-line arguments args = parser.parse_args() # Use the list of integers in your script print(args.int_list)
🌐
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.
🌐
Python documentation
docs.python.org › 3 › howto › argparse.html
Argparse Tutorial — Python 3.14.4 documentation
author, Tshepang Mbambo,. This tutorial is intended to be a gentle introduction to argparse, the recommended command-line parsing module in the Python standard library. Concepts: Let’s show the sor...
🌐
Mimo
mimo.org › glossary › python › argparse
Python argparse: Syntax, Usage, and Examples
Now args.ids is ['1', '2', '3']. This approach lets you handle python argparse list inputs without post-processing.
🌐
Python Module of the Week
pymotw.com › 2 › argparse
argparse – Command line option and argument parsing. - Python Module of the Week
If the argument allows multiple values, values will be a list even if it only contains one item. The value of option_string also depends on the original argument specifiation. For positional, required, arguments, option_string is always None. $ python argparse_custom_action.py Initializing CustomAction dest = 'a' option_strings = ['-a'] required = False Initializing CustomAction dest = 'm' nargs = '*' option_strings = ['-m'] required = False Initializing CustomAction dest = 'positional' option_strings = [] required = True Processing CustomAction for "a" parser = 4299616464 values = 'value' option_string = '-a' Processing CustomAction for "m" parser = 4299616464 values = ['multi-value'] option_string = '-m' Processing CustomAction for "positional" parser = 4299616464 values = 'positional-value' option_string = None Namespace(a='VALUE', m=['MULTI-VALUE'], positional='POSITIONAL-VALUE')
🌐
Real Python
realpython.com › command-line-interfaces-python-argparse
Build Command-Line Interfaces With Python's argparse – Real Python
December 14, 2024 - $ python ls.py -h usage: ls [-h] [-l] path List the content of a directory positional arguments: path options: -h, --help show this help message and exit -l, --long Thanks for using ls! :) Now the output shows the description message right after the usage message and the epilog message at the end of the help text. Help groups are another interesting feature of argparse.
Find elsewhere
🌐
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 - Copied!import argparse parser = argparse.ArgumentParser( description='A sample Argument Parser.' ) parser.add_argument('-l', '--list', nargs='+', required=True) args = parser.parse_args() print(args.list) ... Now open your terminal in the same directory as the main.py file and issue the following command. ... Copied!# ['bobby', 'hadz', '.', 'com'] python main.py --list bobby hadz .
🌐
Kodeclik
kodeclik.com › python-argumentparser-list
Passing a list as a command-line argument to Python
September 24, 2024 - In our case, assume that instead of adding two numbers we desire to add a list of numbers, i.e., a list whose length is not predetermined. To handle such scenarios, we can use the nargs parameter of the add_argument method.
🌐
DataCamp
datacamp.com › tutorial › python-argparse
Master Python's argparse Module: Build Better CLIs | DataCamp
December 3, 2024 - When developing command-line programs in Python, you may encounter scenarios requiring more complex argument parsing. Python's argparse module includes several features to address these complex requirements, allowing you to develop flexible and user-friendly interfaces.
🌐
mkaz.blog
mkaz.blog › working-with-python › argparse
Parse Command-Line Arguments with Argparse
September 19, 2025 - Since sys.argv is simply a list, you can grab blocks of arguments together or slice around as you would any other list. ... import sys if len(sys.argv) > 1: print(f"Script: {sys.argv[0]}") print(f"All arguments: {sys.argv[1:]}") print(f"Last argument: {sys.argv[-1]}") print(f"Arguments 2-end: {' '.join(sys.argv[2:])}") else: print("No arguments provided") ... $ python test.py first second third Script: test.py All arguments: ['first', 'second', 'third'] Last argument: third Arguments 2-end: second third · Use argparse when you want to include flags (e.g., --help), handle optional arguments, or manage arguments with varying lengths.
🌐
Python
bugs.python.org › issue16399
Issue 16399: argparse: append action with default list adds to list instead of overriding - Python tracker
November 4, 2012 - 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/60603
🌐
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('...
🌐
GeeksforGeeks
geeksforgeeks.org › command-line-option-and-argument-parsing-using-argparse-in-python
Command-Line Option and Argument Parsing using argparse in Python - GeeksforGeeks
August 14, 2024 - Argparse is a Python library used to parse command-line arguments in a user-friendly manner. It makes it easy to write user-friendly command-line interfaces, and it is widely used in Python applications.
🌐
Tuxevara
tuxevara.de › 2015 › 01 › pythons-argparse-and-lists
Python’s argparse and lists – Tuxevaras Blog
January 21, 2015 - def csv_list(string): return string.split(',') parser = argparse.ArgumentParser() parser.add_argument('-l', type = csv_list) parser.parse_args()
🌐
Python.org
discuss.python.org › ideas
--advanced-help for argparse - Ideas - Discussions on Python.org
October 25, 2022 - When using argparse, users can get a list of parameters by passing the -h or --help parameter. Sometimes, it’d be nice to hide debug parameters or rare usage parameters from the list of help and only show these w/ an --advanced-help parameter.
🌐
Embl-community
grp-bio-it-workshops.embl-community.io › intermediate-python › 04-argparse › index.html
Parsing Command Line Arguments – Intermediate Python
July 24, 2020 - usage: argparse_example2.py [-h] input_file positional arguments: input_file path to an input file for processing optional arguments: -h, --help show this help message and exit · The example above shows how the program’s help message has been updated to list this positional argument, along with the description we provided about it with the help parameter.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-argparse-to-write-command-line-programs-in-python
How To Use argparse to Write Command-Line Programs in Python | DigitalOcean
March 11, 2021 - As you may have guessed, the -h ... variant python3 aquarium.py --help) prints out the help text. The help text, effectively, is a longer version of the usage text that was outputted in the previous example when you supplied invalid arguments. Notably, the help text also includes the custom description string of List fish in an aquarium that you instantiated the ArgumentParser with earlier on in this tutorial. By default, when you write a CLI using argparse you’ll ...