Python *args and **kwargs Arguments Explained with Examples

In Python, *args and **kwargs are used to handle a variable number of arguments in functions.

Syntax

def function_name(*args, **kwargs):
    # Function implementation

Parameters

  • *args:Tuple, it stores multiple positional arguments to be passed to a function.
  • **kwargs: dictionary, it stores multiple keyword arguments to be passed to a function.

*args Arguments Example

def sum_values(*args):
    print(type(args)) #<class 'tuple'>
    total = sum(args)
    return total

result = sum_values(1, 2, 3, 4, 5)
print(result)  # Output: 15

In this example, the sum_values function takes a variable number of positional arguments using *args. It calculates the sum of all the numbers passed to the function.

**kwargs Arguments Exampe

def print_info(**kwargs):
    print(type(kwargs))
    for key, value in kwargs.items():
        print(f"{key}: {value}")

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

# Output:
# name: Alice
# age: 30
# city: New York

In this example, the print_info function takes a variable number of keyword arguments using **kwargs. It prints out the key-value pairs passed to the function.

*args and **kwargs Arguments Example

def display_info(*args, **kwargs):
    for arg in args:
        print(arg)
    for key, value in kwargs.items():
        print(f"{key}: {value}")

display_info(1, 2, name="Alice", city="London")

# Output:
# 1
# 2
# name: Alice
# city: London

In this combined example, the display_info function accepts both *args and **kwargs. It can handle both positional and keyword arguments in one function call.