0 votes
1 view
in Python by (6.5k points)

I am trying to pass a list as an argument to a command line program. Is there an argparse option to pass a list as option?

parser.add_argument('-l', '--list',

type=list, action='store',


help='<Required> Set flag',


The script is called like below

python test.py -l "265340 268738 270774 270817"

1 Answer

0 votes
by (107k points)

There are many ways to pass a list as an argument to a command-line program some of the important methods are as follows:-

You can pass a delimited string. The reason to pass delimited string is as follows:-

Because the list can be of any type int or str, and sometimes using nargs is good if there are multiple optional arguments and positional arguments. Below is the code that shows how to use the delimited string:-

import argparse

parser = argparse.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(',')]

You can call the script as follows:-

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


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

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

Related questions

0 votes
1 answer
+1 vote
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 5, 2019 in Python by selena (1.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !