Python argparse: Pass a List as command-line argument

avatar
Borislav Hadzhiev

Last updated: Apr 13, 2024
5 min

banner

# Table of Contents

  1. Python argparse: Pass a List as command-line argument
  2. Setting nargs to "*"
  3. Pass a List as command-line argument with action set to "append"
  4. Pass a List of integers as command-line argument
  5. Pass a List as command-line argument using string-delimited values
  6. Pass a command-line argument from a predefined list of values

# Python argparse: Pass a List as command-line argument

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.

main.py
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)
The code for this article is available on GitHub

Now open your terminal in the same directory as the main.py file and issue the following command.

shell
# ['bobby', 'hadz', '.', 'com'] python main.py --list bobby hadz . com

pass list as command line argument in python argparse

Make sure that you haven't set type=list when calling parser.add_argument().

Notice that all arguments are gathered into a list that you can access on the args object.

main.py
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.

main.py
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)
The code for this article is available on GitHub

And here is the code that passes the multiple command-line arguments as a list.

shell
python main.py --employees Alice Bobby Carl

make sure to access correct attribute

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.

# Setting 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.

main.py
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)
The code for this article is available on GitHub

Suppose we run the Python script with the following commands.

shell
# ['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.

shell
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.

shell
# ๐Ÿ‘‡๏ธ None python main.py # ๐Ÿ‘‡๏ธ [] python main.py --employees

without required true

As shown in the screenshot, if the --employees argument is not supplied at all, args.employees is set to None.

# Pass a List as command-line argument with action set to "append"

You can also set the action argument to "append" to group command line arguments into a list.

main.py
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)
The code for this article is available on GitHub

However, now you have to pass multiple argument name-value pairs.

shell
# ['Alice', 'Bobby', 'Carl', 'Dan'] python main.py -e Alice -e Bobby -e Carl -e Dan

pass list command line argument with append

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.

# Pass a List of integers as command-line argument

If you need to pass a list of integers as a command line argument, set the type argument to int.

main.py
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)
The code for this article is available on GitHub

Here is an example of running the Python script.

shell
# ๐Ÿ‘‡๏ธ [10, 15, 20] python main.py --list 10 15 20

taking list of integers as command line arguments

When the type argument is set to int all of the supplied command-line values are expected to be integers.

# Pass a List as command-line argument using string-delimited values

Alternatively, you can use string-delimited values.

main.py
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.

shell
# ['a', 'b', 'c'] python main.py --list a,b,c

list of comma delimited values

The code for this article is available on GitHub

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.

main.py
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.

shell
# [10, 15, 20] python main.py --list 10,15,20

get list of integers result

We used a list comprehension to iterate over the list of strings.

main.py
# [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.

main.py
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.

shell
# [10, 15, 20] python main.py --list 10,15,20

set type argument to lambda function

The lambda function gets called with the supplied comma-separated string, splits it and converts the individual values to integers.

# Pass a command-line argument from a predefined list of values

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().

main.py
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)
The code for this article is available on GitHub

You can now run the program as follows.

shell
# ๐Ÿ‘‡๏ธ 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.

pass command line argument from predefined list

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev