Last modified: Apr 10, 2026 By Alexander Williams
Python Argparse List of Strings Guide
Command-line interfaces (CLIs) make scripts powerful. They let users pass data when they run your program. Python's argparse module is the standard tool for building these interfaces.
Often, you need to accept multiple values for a single option. A common need is to handle a list of strings. This guide shows you exactly how to do that.
Why Use a List of Strings?
Single arguments are simple. But many tasks require multiple inputs.
Imagine a file processor. A user might want to specify several files to convert. Or a data filter that needs multiple keywords. Passing these as a list is clean and intuitive.
Without a list, users must repeat the flag for each item. This is messy. Using argparse to collect them into a list is the professional solution.
Basic Setup with Argparse
First, import the module and create a parser. This is the foundation for all command-line parsing.
import argparse
# Create the argument parser object
parser = argparse.ArgumentParser(description='Process some strings.')
The ArgumentParser object holds all your argument definitions. The description helps users understand your script's purpose.
The nargs Parameter: Your Key to Lists
The magic happens with the nargs parameter. It tells argparse how many arguments to expect for one option.
To collect a list, you typically use nargs='+' or nargs='*'.
'+' means one or more items are required. The user must provide at least one value.
'*' means zero or more items are allowed. The list can be empty if the user doesn't provide the flag.
Example: Required List of Files
Let's build a script that processes files. We'll require at least one filename.
import argparse
parser = argparse.ArgumentParser(description='Process input files.')
# 'nargs=+' collects one or more arguments into a list
parser.add_argument('--files', '-f', nargs='+', help='Input file names')
args = parser.parse_args()
print(f"Files to process: {args.files}")
print(f"Type of 'files': {type(args.files)}")
Now, run it from the command line.
$ python script.py --files data1.txt data2.txt report.pdf
Files to process: ['data1.txt', 'data2.txt', 'report.pdf']
Type of 'files': <class 'list'>
The arguments are collected into a Python list. You can loop through args.files easily.
If you run it without --files, you'll get an error. This is because nargs='+' requires at least one argument. For more on controlling argument requirements, see our guide on Python Argparse Optional Arguments.
Example: Optional List of Tags
Sometimes a list is optional. Use nargs='*' for that.
import argparse
parser = argparse.ArgumentParser(description='Filter data with tags.')
# 'nargs=*' collects zero or more arguments into a list
parser.add_argument('--tags', '-t', nargs='*', default=['untagged'], help='Filter tags (optional)')
args = parser.parse_args()
print(f"Active tags: {args.tags}")
$ python script.py --tags urgent python bug
Active tags: ['urgent', 'python', 'bug']
$ python script.py
Active tags: ['untagged']
When no tags are given, the list uses the default value we set. Using default effectively is crucial. Learn more in our Python Argparse Default Value Guide.
Using a Fixed Number of Arguments (nargs=N)
You can also demand an exact number of items. Use nargs=N where N is a number.
This is useful for coordinate pairs or name-value combinations.
import argparse
parser = argparse.ArgumentParser(description='Plot a point.')
# 'nargs=2' expects exactly two following arguments
parser.add_argument('--coordinates', '-c', nargs=2, type=float, help='X and Y coordinates (e.g., 5.0 10.2)')
args = parser.parse_args()
if args.coordinates:
x, y = args.coordinates
print(f"Plotting point at X={x}, Y={y}")
$ python script.py --coordinates 5.5 12.8
Plotting point at X=5.5, Y=12.8
Combining List Arguments with Other Flags
Real scripts often mix list arguments with other types like booleans or single values.
argparse handles this seamlessly. It knows where one argument ends and the next begins.
import argparse
parser = argparse.ArgumentParser(description='Advanced file operations.')
parser.add_argument('--files', nargs='+', help='List of input files')
parser.add_argument('--verbose', '-v', action='store_true', help='Enable verbose output')
parser.add_argument('--output', '-o', help='Single output file name')
args = parser.parse_args()
if args.verbose:
print("Verbose mode enabled.")
if args.files:
print(f"Processing {len(args.files)} file(s): {args.files}")
if args.output:
print(f"Output will be saved to: {args.output}")
$ python script.py --files a.txt b.txt --output result.txt -v
Verbose mode enabled.
Processing 2 file(s): ['a.txt', 'b.txt']
Output will be saved to: result.txt
The action='store_true' parameter creates a simple boolean flag. For a deeper dive into this pattern, check out our Python Argparse Boolean Flags Guide.
Common Pitfalls and Best Practices
Handling lists is straightforward if you avoid these common mistakes.
Pitfall 1: Forgetting the nargs parameter. Without nargs, only the last value is stored, overwriting previous ones.
Pitfall 2: Confusing '+' and '*'. Remember, '+' requires at least one argument. '*' makes the list optional.
Best Practice: Always set a default. For optional lists (nargs='*'), explicitly set default=[] (an empty list). This is clearer than relying on None.
Best Practice: Use descriptive help text. Tell the user they can provide multiple items. Example: help="One or more filenames (separated by spaces)".
Conclusion
Accepting a list of strings with Python's argparse is simple and powerful. The key is the nargs parameter.
Use nargs='+' for a required list. Use nargs='*' for an optional list. Use nargs=N for a fixed number of items.
This technique makes your CLI scripts flexible and user-friendly. Users can pass multiple items cleanly without complex syntax.
Combine list arguments with other types like flags and single values. Remember to set sensible defaults and write clear help messages.
Now you can build robust command-line tools that handle real-world data efficiently.