Python *args and **kwargs

In Python, *args and **kwargs allow functions to accept a variable number of arguments.
1. *args: Lets you pass a variable number of non-keyword (positional) arguments to a function.
2. **kwargs: Lets you pass a variable number of keyword arguments (i.e., named arguments) to a function.

1. Using *args for Variable Positional Arguments

*args collects extra positional arguments passed to a function into a tuple.
def add_numbers(*args):
    result = sum(args)
    print("Sum:", result)

add_numbers(1, 2, 3, 4, 5)

Output:

Sum: 15
Explanation: The *args collects the arguments (1, 2, 3, 4, 5) into a tuple, allowing the function to process any number of arguments.

2. Mixing Regular Arguments with *args

It is possible to combine regular arguments with *args, where regular arguments must come first.
def greet_people(greeting, *args):
    for person in args:
        print(f"{greeting}, {person}!")

greet_people("Hello", "Alice", "Bob", "Charlie")

Output:

Hello, Alice!
Hello, Bob!
Hello, Charlie!
Explanation: The greeting parameter is a regular argument, followed by *args, which collects additional names passed to the function.

3. Using **kwargs for Variable Keyword Arguments

**kwargs allows you to pass variable keyword arguments, which it collects into a dictionary.
def print_person_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_person_info(name="Alice", age=30, city="New York")

Output:

name: Alice
age: 30
city: New York
Explanation: The **kwargs collects the arguments (name="Alice", age=30, city="New York") into a dictionary, allowing easy access to each key-value pair.

4. Mixing Regular Arguments with **kwargs

When mixing regular arguments with **kwargs, the regular arguments come first.
def introduce_person(title, **kwargs):
    print(f"Title: {title}")
    for key, value in kwargs.items():
        print(f"{key}: {value}")

introduce_person("Engineer", name="Alice", age=30, city="New York")

Output:

Title: Engineer
name: Alice
age: 30
city: New York
Explanation: The function takes title as a regular argument and additional keyword arguments as **kwargs.

5. Using Both *args and **kwargs

You can use both *args and **kwargs in the same function. In this case, *args must appear before **kwargs.
def show_info(*args, **kwargs):
    print("Positional arguments:", args)
    print("Keyword arguments:", kwargs)

show_info("Alice", "Engineer", age=30, city="New York")

Output:

Positional arguments: ('Alice', 'Engineer')
Keyword arguments: {'age': 30, 'city': 'New York'}
Explanation: This function can handle both positional and keyword arguments, making it highly flexible.

6. Using *args and **kwargs to Unpack Arguments

*args and **kwargs can also be used to unpack existing lists or dictionaries when calling a function.
def order(food, drink):
    print(f"Food: {food}, Drink: {drink}")

args = ("Burger", "Soda")
order(*args)

kwargs = {"food": "Pizza", "drink": "Water"}
order(**kwargs)

Output:

Food: Burger, Drink: Soda
Food: Pizza, Drink: Water
Explanation: By using *args and **kwargs, we can unpack lists or dictionaries directly when calling a function.

In summary, *args and **kwargs make functions flexible and allow for dynamic argument handling. They are widely used in scenarios where the number or type of arguments may vary.

Previous: Python Scope | Next: Python Package

<
>