Variable Length Arguments in Python

In Python, you can use formal arguments (also known as positional or keyword arguments), a non-keyworded variable-length argument list (*args), and a keyword variable-length argument list (**kwargs) together in the same function. The function signature should follow a specific order:

  1. Positional/Keyword arguments: These are your regular function parameters.

  2. *args: This captures additional positional arguments as a tuple.

  3. **kwargs: This captures additional keyword arguments as a dictionary.

Example of Using All Three Together

def example_function(arg1, arg2, *args, **kwargs):
    print(f"arg1: {arg1}")
    print(f"arg2: {arg2}")
    
    # Handling *args
    print("Additional positional arguments (*args):")
    for arg in args:
        print(arg)
    
    # Handling **kwargs
    print("Additional keyword arguments (**kwargs):")
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# Example call
example_function(10, 20, 30, 40, 50, name="Alice", age=30, city="New York")

Explanation

  • Formal Arguments (arg1, arg2): These are the standard positional/keyword arguments that must be provided when calling the function.

  • Non-keyworded Variable Length Argument List (*args): This captures any additional positional arguments passed to the function as a tuple. In the example above, 30, 40, and 50 are captured by *args.

  • Keyword Variable Length Argument List (**kwargs): This captures any additional keyword arguments passed to the function as a dictionary. In the example above, name="Alice", age=30, and city="New York" are captured by **kwargs.

Output

When calling example_function(10, 20, 30, 40, 50, name="Alice", age=30, city="New York"), the output will be:

arg1: 10
arg2: 20
Additional positional arguments (*args):
30
40
50
Additional keyword arguments (**kwargs):
name: Alice
age: 30
city: New York

Order of Arguments

In the function signature:

  • Formal arguments come first.

  • *args comes next to capture any extra positional arguments.

  • **kwargs comes last to capture any extra keyword arguments.

This structure ensures that the function can handle a mix of fixed and flexible numbers of arguments.

Last updated

Was this helpful?