
Last updated: Apr 13, 2024
Reading timeยท5 min

The easiest way to pass a list as a command-line argument is to set the
nargs argument to "+" when calling add_argument().
When the nargs argument is set to "+", all of the supplied command-line
arguments are gathered into a list.
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.
# ['bobby', 'hadz', '.', 'com'] python main.py --list bobby hadz . com

type=list when calling parser.add_argument().Notice that all arguments are gathered into a list that you can access on the
args object.
args = parser.parse_args() # ๐๏ธ ['bobby', 'hadz', '.', 'com'] print(args.list)
Make sure you try to access the correct attribute on the object.
For example, if your list is named employees, you would use args.employees.
import argparse parser = argparse.ArgumentParser( description='A sample Argument Parser.' ) parser.add_argument('-e', '--employees', nargs='+', required=True) args = parser.parse_args() # ๐๏ธ ['Alice', 'Bobby', 'Carl'] print(args.employees)
And here is the code that passes the multiple command-line arguments as a list.
python main.py --employees Alice Bobby Carl

The nargs keyword argument associates a different number of command-line arguments with a single action.
When nargs is set to "+", all supplied command-line arguments are gathered
into a list.
An error message is generated if you don't supply at least one argument.
nargs to "*"If the list argument is optional (and not required), set the nargs argument to
"*".
By setting the nargs argument to an asterisk "*", no error is raised if the
argument isn't supplied.
import argparse parser = argparse.ArgumentParser( description='A sample Argument Parser.' ) parser.add_argument('-e', '--employees', nargs='*', required=True) args = parser.parse_args() print(args.employees)
Suppose we run the Python script with the following commands.
# ['Alice', 'Bobby', 'Carl'] python main.py --employees Alice Bobby Carl # [] python main.py --employees
The "*" value also gathers all supplied arguments into a list.
However, no error is raised if no values are supplied for the argument.
If you remove the required=True argument and don't supply the --employees
command line argument, args.employees will be set to None.
import argparse parser = argparse.ArgumentParser( description='A sample Argument Parser.' ) parser.add_argument('-e', '--employees', nargs='*') args = parser.parse_args() print(args.employees)
Suppose, you run the script as follows.
# ๐๏ธ None python main.py # ๐๏ธ [] python main.py --employees

As shown in the screenshot, if the --employees argument is not supplied at
all, args.employees is set to None.
action set to "append"You can also set the action argument to "append" to group command line
arguments into a list.
import argparse parser = argparse.ArgumentParser( description='A sample Argument Parser.' ) parser.add_argument('-e', '--employees', action='append', required=True) args = parser.parse_args() print(args.employees)
However, now you have to pass multiple argument name-value pairs.
# ['Alice', 'Bobby', 'Carl', 'Dan'] python main.py -e Alice -e Bobby -e Carl -e Dan

Notice that we passed the same argument multiple times.
All of the supplied values are gathered into a list that you can access via
args.employees.
The action argument determines how the command-line arguments are handled.
The append action stores a list and appends each argument value to the list.
It is mostly used when you want to enable the user to specify the same argument multiple times.
If you need to pass a list of integers as a command line argument, set the
type argument to int.
import argparse parser = argparse.ArgumentParser( description='A sample Argument Parser.' ) parser.add_argument('-l', '--list', nargs='+', type=int, required=True) args = parser.parse_args() print(args.list)
Here is an example of running the Python script.
# ๐๏ธ [10, 15, 20] python main.py --list 10 15 20

When the type argument is set to int all of the supplied command-line values
are expected to be integers.
Alternatively, you can use string-delimited values.
import argparse parser = argparse.ArgumentParser( description='A sample Argument Parser.' ) parser.add_argument('-l', '--list', help='Supply string-delimited values', type=str) args = parser.parse_args() result = args.list.split(',') print(result)
You can run the script as follows.
# ['a', 'b', 'c'] python main.py --list a,b,c

Notice that we passed the argument's values as a comma-separated string.
If you want to get the result as a list of integers, use a list comprehension.
import argparse parser = argparse.ArgumentParser( description='A sample Argument Parser.' ) parser.add_argument('-l', '--list', help='Supply string-delimited values', type=str) args = parser.parse_args() result = [int(x) for x in args.list.split(',')] print(result)
Here is an example of running the program.
# [10, 15, 20] python main.py --list 10,15,20

We used a list comprehension to iterate over the list of strings.
# [10, 15, 20] result = [int(x) for x in args.list.split(',')]
On each iteration, we use the int() class to convert the current string to an integer.
The result variable stores a list of integers in the end.
Note that you can achieve the same result by setting the type argument to
lambda function.
import argparse parser = argparse.ArgumentParser( description='A sample Argument Parser.' ) parser.add_argument('-l', '--list', help='Supply string-delimited integers', type=lambda string: [ int(x) for x in string.split(',')] ) args = parser.parse_args() print(args.list)
Here is an example of running the program.
# [10, 15, 20] python main.py --list 10,15,20

The lambda function gets called with the supplied comma-separated string, splits it and converts the individual values to integers.
If you need to pass a command-line argument from a predefined list of values,
use the choices argument in the call to parser.add_argument().
import argparse parser = argparse.ArgumentParser( description='A sample Argument Parser.' ) parser.add_argument('-f', '--fruit', choices=['apple', 'banana', 'pear'] ) args = parser.parse_args() print(args.fruit)
You can now run the program as follows.
# ๐๏ธ apple python main.py --fruit apple # --------------------------------------------------- # usage: main.py [-h] [-f {apple,banana,pear}] # main.py: error: argument -f/--fruit: invalid choice: 'melon' (choose from 'apple', 'banana', 'pear') main.py --fruit melon
If you supply one of the values that are contained in the choices list,
everything works as expected.
If you supply a different value, you get an error noting that you should only
select one of the values from the choices list.

You can learn more about the related topics by checking out the following tutorials:
__main__ module in Path