Skip to main content

How to Pass Lists as Command-Line Arguments with argparse in Python

This guide explains how to accept lists of values as command-line arguments in your Python scripts using the argparse module.

We'll cover different techniques for handling lists of strings, integers, and other data types, along with using delimiters and restricting input to a predefined set of choices.

Using nargs='+' for One or More Arguments

The nargs='+' option is the most straightforward way to accept a variable number of arguments, collecting them into a list. It requires at least one argument to be provided.

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)

Usage example:

python main.py --list tutorial reference . com
# Output: ['tutorial', 'reference', '.', 'com']

python main.py --list # This will cause an error: expected at least one argument
  • nargs='+': This tells argparse to gather all positional arguments for this option into a list. The user must provide at least one value.
  • required=True: Makes the argument mandatory. If you need it to be optional, leave this off and check for None, or set the default value to an empty list ([]).
  • The arguments will be of type string.

Using nargs='*' for Zero or More Arguments

If the list argument should be optional, use nargs='*'. This allows the user to provide zero or more arguments:

import argparse

parser = argparse.ArgumentParser(description='A sample Argument Parser.')
parser.add_argument('-e', '--employees', nargs='*') # No 'required=True'

args = parser.parse_args()
print(args.employees)

Usage example:

python main.py --employees Alice Bob Carl
# Output: ['Alice', 'Bob', 'Carl']

python main.py --employees
# Output: []

python main.py
# Output: None
  • If no arguments are provided to --employees, args.employees will be None.
  • nargs='*': Gathers all positional arguments into a list, including zero arguments.
  • The arguments will be strings.
  • If nargs='*' and required=True this will cause error if no arguments are supplied.

Using action='append' for Multiple Occurrences

If you want the user to be able to specify the same argument multiple times, and collect all the values into a list, use action='append':

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)

Usage example:

python main.py -e Alice -e Bob -e Carl
# Output: ['Alice', 'Bob', 'Carl']
  • action='append' appends each value provided for the argument to a list. This is different from nargs, which expects all values to be provided together.
  • The elements will be strings.

Specifying the Type of List Elements

By default, command-line arguments are treated as strings. To get a list of integers (or floats, etc.), use the type argument:

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)

Usage example:

python main.py --list 10 15 20
# Output: [10, 15, 20]
  • All elements passed will be converted to integers using int().
  • type=int: This tells argparse to convert each argument value to an integer. You can use type=float for floats, or any other callable that takes a string and returns the desired type.

While it's possible to have the user provide a single string with a delimiter (like a comma) and then split it, this is less user-friendly than using nargs or action. It's better to let argparse handle the argument parsing.

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

if args.list: # Check if list is not None
result = [int(x) for x in args.list.split(',')]
print(result) # Output: [10, 15, 20]
else:
print("No list provided.")
# Usage:
# python main.py --list 10,15,20
  • The program takes a string, splits it by comma, and converts the values to integers.
  • This is less recommended as it is less user friendly.

Restricting Choices with choices

If you want to restrict the allowed values for the list, use the choices 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)

# Usage:
# python main.py --fruit apple # Output: apple
# python main.py --fruit orange # Error: invalid choice
  • The allowed values can be passed to choices as a list.
  • This will only allow the arguments passed to be from a specified list of values.