Last modified: Apr 10, 2026 By Alexander Williams

Python Argparse Multiple Values Tutorial

Command-line interfaces (CLIs) make tools powerful. They allow users to pass data and options when running a script. The Python argparse module is the standard way to build these interfaces.

Often, you need an argument that can accept more than one value. For example, you might want to process a list of files or a set of numbers. This tutorial shows you how to handle multiple values with argparse.

We will cover the nargs parameter, type handling, and custom actions. You will learn to create flexible and user-friendly command-line tools.

Why Use Multiple Values in Arguments?

Single-value arguments are common. But many tasks require collections of data. Think of a script that resizes images. You might want to pass several image filenames at once.

Another example is a data filtering tool. You could accept multiple criteria or threshold values. Handling these as a list is more efficient than defining many separate arguments.

Using argparse for this keeps your code clean. It also provides automatic help text and error messages. Users will understand how to supply the data correctly.

The Core: The nargs Parameter

The key to accepting multiple values is the nargs keyword argument in add_argument(). It tells argparse how many command-line arguments should be consumed for this option.

You can set nargs to a specific number, like 3. You can also use special characters like '*', '+', or '?'. The values are gathered into a list.

Let's look at the most useful nargs values.

nargs='*' (Zero or More Values)

This is the most common choice for a list. It gathers all the following command-line arguments into a list. If no arguments are provided, it results in an empty list.

It is perfect for optional lists of items, like input files.


import argparse

parser = argparse.ArgumentParser(description="Process files.")
# The 'files' argument will collect all provided strings into a list.
parser.add_argument('files', nargs='*', help="Input filenames")

args = parser.parse_args()
print(f"Files to process: {args.files}")
print(f"Type of files: {type(args.files)}")

# Example runs
$ python script.py image1.jpg image2.png
Files to process: ['image1.jpg', 'image2.png']
Type of files: <class 'list'>

$ python script.py
Files to process: []
Type of files: <class 'list'>

nargs='+' (One or More Values)

This is like '*' but requires at least one value. If the user provides zero arguments, argparse will show an error. Use this when your script cannot run without at least one item.


parser = argparse.ArgumentParser()
parser.add_argument('numbers', nargs='+', type=int, help="At least one integer")

args = parser.parse_args()
print(f"Sum: {sum(args.numbers)}")

$ python script.py 5 10 15
Sum: 30

$ python script.py
usage: script.py [-h] numbers [numbers ...]
script.py: error: the following arguments are required: numbers

nargs=N (An Exact Number)

You can specify an exact number of arguments. Replace N with an integer. For instance, nargs=2 is common for coordinates (x, y) or a key-value pair.


parser = argparse.ArgumentParser()
parser.add_argument('coordinates', nargs=2, type=float, help="X and Y coordinates")

args = parser.parse_args()
x, y = args.coordinates
print(f"Point is at ({x}, {y})")

$ python script.py 3.5 7.2
Point is at (3.5, 7.2)

Combining with Type Conversion

The type parameter works seamlessly with nargs. The specified type is applied to each value collected in the list. This is great for lists of integers or floats.

Our previous sum example used type=int. Here is another example for custom types.


def valid_grade(value):
    ivalue = int(value)
    if ivalue < 0 or ivalue > 100:
        raise argparse.ArgumentTypeError(f"Grade {value} must be 0-100")
    return ivalue

parser = argparse.ArgumentParser()
parser.add_argument('grades', nargs='+', type=valid_grade, help="List of grades (0-100)")

args = parser.parse_args()
print(f"Average grade: {sum(args.grades)/len(args.grades):.1f}")

Using with Optional Arguments (-f, --flag)

The nargs parameter also works with optional flags (arguments starting with - or --). This creates a powerful interface. For more on defining these, see our Python Argparse Optional Arguments Guide.

You can have a flag like --scores that accepts multiple numbers.


parser = argparse.ArgumentParser()
parser.add_argument('--scores', nargs='+', type=int, default=[], help="List of scores")

args = parser.parse_args()
if args.scores:
    print(f"High score: {max(args.scores)}")

$ python script.py --scores 85 92 78
High score: 92

Custom Actions for Advanced Control

Sometimes, you need more control than nargs and type provide. You can create a custom action by subclassing argparse.Action. This lets you process the multiple values in a unique way.

For example, you could convert the list to a set or a tuple. Or you could perform immediate validation across all values.


import argparse

class UniqueListAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        # 'values' is the list collected by nargs
        unique_values = list(set(values))  # Remove duplicates
        setattr(namespace, self.dest, unique_values)

parser = argparse.ArgumentParser()
parser.add_argument('--tags', nargs='+', action=UniqueListAction, default=[], help="Unique tags")

args = parser.parse_args()
print(f"Unique tags: {args.tags}")

$ python script.py --tags python cli python argparse
Unique tags: ['argparse', 'python', 'cli']

Common Pitfalls and Best Practices

Using multiple values is straightforward. But watch out for a few things.

Mixing positional and optional arguments: When you have a positional argument with nargs='*', place it at the end. Otherwise, it may consume arguments meant for later options.

Setting a default list: Be careful with mutable defaults like default=[]. It's usually safe with argparse, but know that it's the same list object for all parses. For more on this, read the Python Argparse Default Value Guide.

Clear help messages: Always explain in the help text that multiple values are expected. For example, use "one or more filenames" or "a list of numbers".

Conclusion

Handling multiple values with Python's argparse is simple and powerful. The nargs parameter is the main tool. Use '*' for optional lists and '+' for required lists.

Combine it with the type parameter for lists of integers or custom types. For ultimate control, implement a custom Action class.

This functionality helps you build professional, user-friendly command-line tools. Your scripts can accept flexible input like file lists, number sets, or configuration parameters. To see these concepts in a full example, check out our Python Argparse Example: Command Line Arguments.

Start using nargs in your next CLI project. It will make your tools more useful and easier to run.