Last modified: Apr 10, 2026 By Alexander Williams
Argparse Python Multiple Values Same Argument
Command-line interfaces are powerful. They let users control your scripts. Python's argparse module is the standard tool for building them. A common need is to let users provide multiple values for one argument.
Think of a script that processes files. You might want to pass several filenames at once. Or a tool that filters data by multiple tags. This guide shows you how.
We will cover the nargs parameter and custom actions. You will learn to collect lists of values efficiently.
Why Use Multiple Values in One Argument?
It makes your scripts more user-friendly. Instead of calling a script many times, users can do it once. It groups related data together logically.
For example, an image converter. A user wants to convert three PNG files to JPG. Without multi-value support, they might need three commands. With it, they use one.
This approach is cleaner. It reduces typing errors. It also makes argument parsing more predictable. Your code handles a list, not many separate variables.
The Core Solution: The nargs Parameter
The key to this is the nargs keyword in add_argument(). It tells argparse how many arguments to expect for this option.
Set nargs='+' to accept one or more values. Set nargs='*' to accept zero or more values. The values are stored as a list in your namespace.
Here is a basic example. We create an argument to accept multiple filenames.
import argparse
# Create the parser
parser = argparse.ArgumentParser(description="Process some files.")
# Add an argument that expects one or more values
parser.add_argument('files', nargs='+', help='Input filenames')
# Parse the arguments
args = parser.parse_args()
# The 'files' attribute is now a list
print(f"Processing {len(args.files)} file(s):")
for f in args.files:
print(f" - {f}")
Run this script from the command line. You will see how it collects values.
$ python script.py file1.txt file2.txt file3.jpg
Processing 3 file(s):
- file1.txt
- file2.txt
- file3.jpg
The script takes all arguments after the script name. It puts them into the args.files list. The nargs='+' means at least one value is required.
If you run it with no arguments, argparse will show an error. This is good for required inputs. For a deeper dive into list handling, see our Python Argparse List of Strings Guide.
Using nargs with Optional Arguments
You can also use nargs with flags that start with -- or -. These are optional arguments. The syntax is slightly different on the command line.
You specify the flag once. Then you provide all its values. Here is an example with a --tag flag.
import argparse
parser = argparse.ArgumentParser()
# This is an optional argument that takes multiple values
parser.add_argument('--tag', nargs='+', help='Tags for filtering')
args = parser.parse_args()
if args.tag:
print(f"Filtering by tags: {args.tag}")
Run the script. Notice how the values follow the flag.
$ python script.py --tag python tutorial argparse
Filtering by tags: ['python', 'tutorial', 'argparse']
The args.tag variable is a list containing ['python', 'tutorial', 'argparse']. This is very useful for filtering or configuration options. For more on optional arguments, check our Python Argparse Optional Arguments Guide.
Understanding nargs Values
The nargs parameter accepts several special characters. Each changes how arguments are consumed.
- '?': Accepts zero or one argument. Good for optional single values.
- '*': Accepts zero or more arguments. Stores them as a list. The list is empty if none given.
- '+': Accepts one or more arguments. Stores them as a list. Requires at least one value.
- An integer (e.g., 3): Accepts exactly that many arguments.
Using an integer is precise. You know exactly how many items you will get. Here is an example expecting three coordinates.
import argparse
parser = argparse.ArgumentParser()
# Expect exactly three numbers for an X, Y, Z coordinate
parser.add_argument('--coords', nargs=3, type=float, help='X Y Z coordinates')
args = parser.parse_args()
if args.coords:
x, y, z = args.coords
print(f"Point at: X={x}, Y={y}, Z={z}")
$ python script.py --coords 10.5 20.0 5.2
Point at: X=10.5, Y=20.0, Z=5.2
Setting a Default Value for List Arguments
What if the user doesn't provide values? With nargs='*' or nargs='?', the list can be empty. You might want a default list.
Be careful. Do not use a mutable list like default=[]. This creates one list object shared across all parser calls. Use default with a type or a custom action.
A safer way is to use default with the type parameter. Or set the default after parsing. For best practices, read our Python Argparse Default Value Guide.
import argparse
# Safer: default is None, then check in code
parser = argparse.ArgumentParser()
parser.add_argument('--items', nargs='*', default=None, help='List of items')
args = parser.parse_args()
# If args.items is None, use an empty list
item_list = args.items if args.items is not None else []
print(f"Items: {item_list}")
Advanced Technique: Custom Action for Multiple Values
Sometimes nargs isn't enough. You might need custom processing. You can create a class that inherits from argparse.Action.
Override the __call__ method. This lets you control how values are stored. It is powerful for complex data.
Imagine you want to collect unique values. A custom action can add to a set. Here is an example.
import argparse
class UniqueAppendAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
# Get the current set or create a new one
items = getattr(namespace, self.dest, set())
# Ensure it's a set
if not isinstance(items, set):
items = set()
# Add the new values (could be one or many from nargs)
if isinstance(values, list):
items.update(values)
else:
items.add(values)
# Save it back to the namespace
setattr(namespace, self.dest, items)
parser = argparse.ArgumentParser()
parser.add_argument('--unique-tag', action=UniqueAppendAction, nargs='+', default=set())
args = parser.parse_args()
print(f"Unique tags: {args.unique_tag}")
$ python script.py --unique-tag aa bb cc --unique-tag aa dd
Unique tags: {'dd', 'aa', 'bb', 'cc'}
The custom action ensures tags are unique. Even if 'aa' is provided twice, it appears once in the set. This is just one use case.
Common Pitfalls and Best Practices
Using multiple values is straightforward. But watch for these issues.
Mixing positional and optional arguments. When you have a positional argument with nargs='+', it consumes all remaining command-line arguments. Place your optional arguments before it.
Using mutable defaults. As mentioned, avoid default=[] or default={}. Use None and convert in your code.
Forgetting the type parameter. All values collected by nargs are strings. Use type=int or type=float to convert them if needed.
Providing clear help text. Tell the user they can provide multiple values. Your help message should indicate this.
Conclusion
Handling multiple values for one argument is essential. The argparse module makes it easy with nargs.
Use nargs='+' for required lists. Use nargs='*' for optional lists. For precise counts, use an integer.
For advanced control, create a custom action class. This lets you validate, transform, or store data uniquely.
Combine this with other argparse features. You can build robust, user-friendly command-line tools. Start by adding a multi-value argument to your next script.