How to pass a list as a command-line argument with argparse?
Last Updated :
24 Apr, 2025
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. In this tutorial, we will discuss how to pass a list as a command-line argument using the Argparse library in Python.
Passing a List as a Command Line Argument with Argparse
To pass a Python list as a command-line argument with the Argparse library, we will use the "nargs" argument in the add_argument() method. The "nargs" stands for "number of arguments", and it tells the argparse how many arguments a specific option should expect.
Steps to pass a List as Command Line Argument with Argparse
Let us see the steps involved in passing lists as command line arguments with Argparse Library in Python.
Step 1: Import the required module
To use the argparse, you need to import the argparse module. You can do this by adding the following line at the beginning of your Python script:
import argparse
Step 2: Create an argument parser
Next, create an argument parser object by calling the ArgumentParser() method:
parser = argparse.ArgumentParser()
Step 3: Add an argument
Add the argument to the argument parser using the add_argument() method. Use the type parameter to specify the data type of the argument, The list can be of any type, a string, an integer, etc.
parser.add_argument("--numbers", type=int)
Step 4: Parse the arguments
Finally, parse the command-line arguments by calling the parse_args() method on the argument parser object. This will return an object that contains the parsed arguments.
args = parser.parse_args()
Step 5: Access the list
You can access the list of integers passed as the "--numbers" argument using the "numbers" attribute of the args object.
print(args.numbers)
Passing a list of Strings
In this example, the list_of_strings function takes a string as input and returns a list of strings. The type parameter of add_argument is set to list_of_strings, so when parse_args is called, the string value of --str-list is converted into a list of strings.
Python3
# import module
import argparse
# Define a custom argument type for a list of strings
def list_of_strings(arg):
return arg.split(',')
# Create an ArgumentParser object
parser = argparse.ArgumentParser()
# Add an argument for the list of strings
parser.add_argument('--str-list', type=list_of_strings)
# Parse the command-line arguments
args = parser.parse_args()
# Use the list of strings in your script
print(args.str_list)
Output:
You can run this script with the following command. Here 'script.py' refers to the name of the saved Python file.
python script.py --str-list foo,bar,baz
Passing a list of strings as command line argumentsNote: Make sure that there is no space between the items of the list, else it can generate an error. We will see how we can resolve this error in the upcoming examples.
Passing a list of Integers
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.
Python3
# 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)
Output:
You can run this script with the following command:
python script.py --int-list 1,2,3,4,5,6
Passing a list of integersPass a List as a Command-Line Argument
Let us see a few examples for Python passing a list as an argument:
Example 1: Passing one or more values using nargs='+'
In this example, we add an argument called "my_list" using the "add_argument" method. The "metavar" parameter is used to specify the argument's name in the usage message. The "type" parameter is set to "str" since we want the list to be a list of strings. The "nargs" parameter is set to "+" to indicate that the argument can take one or more values.
Python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('my_list', metavar='N', type=str, nargs='+',
help='a list of strings')
args = parser.parse_args()
print(args.my_list)
Output:
Passing only one argument:
python my_script.py geeksforgeeks
Passing only one value using nargs='+'Passing more than one argument:
python my_script.py geeks for geeks
Passing more than one value using nargs='+'Example 2: Passing zero or more values using nargs='*'
In this example, the 'nargs' parameter is set to '*' to indicate that the argument can take zero or more values. Here, we are in Python passing a list as an argument.
Python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('my_list', metavar='N', type=str, nargs='*',
help='a list of strings')
args = parser.parse_args()
print(args.my_list)
Output:
Passing zero arguments:
python my_script.py
Passing zero value using nargs='*'Passing more than zero arguments or Python passing a list as an argument:
python my_script.py geeks for geeks
Passing more than zero values using nargs='*'Example 3: Passing Optional Arguments
In this example, we provided two arguments, one is compulsory and the other is optional. We set the 'required' parameter to 'True' which means it is a compulsory one. In the second argument, we did not define the required parameter, which means it is an optional argument.
Python3
# import module
import argparse
parser = argparse.ArgumentParser()
# first argument
parser.add_argument('--string1', type=str, required=True)
# second argument optional
parser.add_argument('--string2', type=str)
args = parser.parse_args()
if args.string2:
print(args.string1, args.string2)
else:
print(args.string1)
Output:
When both arguments are defined:
python my_script.py --string1 Hello --string2 world
Passing optional arguments as command line argumentWhen the optional parameter is not defined:
python my_script.py --string1 Hello
Without passing optional arguments as command line argument
Similar Reads
Pass list as command line argument in Python
The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. One of them is sys module. sys Module A module is a file containing Python definiti
3 min read
How to handle invalid arguments with argparse in Python?
Argparse module provides facilities to improve the command-line interface. The methods associated with this module makes it easy to code for command-line interface programs as well as the interaction better. This module automatically generates help messages and raises an error when inappropriate arg
4 min read
Command-Line Option and Argument Parsing using argparse in Python
Command line arguments are those values that are passed during the calling of the program along with the calling statement. Usually, python uses sys.argv array to deal with such arguments but here we describe how it can be made more resourceful and user-friendly by employing argparse module. Python
8 min read
How to Parse Command Line Arguments in Node ?
Command-line arguments, in the context of a command-line interface (CLI), are text strings that provide extra information to a program when it is executed. In Nodejs, these arguments are accessible through an array known as argv (arguments values), where the shell passes all received command-line ar
3 min read
Bash Script - How to use Command Line Arguments
In this article, let us see about Command Line Arguments usage in Bash script. Arguments are inputs that are necessary to process the flow. Instead of getting input from a shell program or assigning it to the program, the arguments are passed in the execution part. Positional Parameters Command-line
4 min read
How to Pass Command Line Arguments to GDB in a Linux Environment?
The GNU Debugger, commonly known as GDB, is a powerful tool used for debugging and analyzing programs in Linux and other Unix-like operating systems. While GDB is commonly used to debug programs, it can also be used to launch programs with specific command line arguments. This article will walk you
6 min read
How to Print Second Command line Argument in shell?
Command line arguments are the parameters we pass to a command or script when we run it from the terminal. These arguments are passed as strings and can be accessed within your program to perform various operations. How to Print Second Command Line Argument in Shell?The shell stores the command line
5 min read
Python | Set 6 (Command Line and Variable Arguments)
Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5) This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python. Command Line Arguments Till now, we have taken input in python using raw_input() or input() [for integers].
2 min read
How to print command line arguments passed to the script in Node.js ?
Node.js is an open-source and cross-platform runtime environment built on Chrome's V8 engine that enables us to use JavaScript outside the browser. Node.js helps us to use build server-side applications using JavaScript. In Node.js if you want to print the command line arguments then we can access
2 min read
Command Line Arguments in Python
The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. The three most common are: Table of Content Using sys.argvUsing getopt moduleUsing
5 min read