Sobes.tech
Junior

Why are *args and **kwargs used in Python?

sobes.tech AI

Answer from AI

*args and **kwargs allow passing a variable number of arguments to a function.

  • *args (arbitrary positional arguments): collects all unnamed arguments into a tuple.
  • **kwargs (arbitrary named arguments): collects all named arguments into a dictionary.

Usage:

  1. Functions with a variable number of parameters: When the number of arguments is unknown in advance.
  2. Decorators: For universally wrapping functions with different signatures.
  3. Call forwarding: When one function calls another, passing the received arguments.
# Example of using *args
def sum_all(*args):
    total = 0
    for num in args:
        total += num
    return total

# Example of using **kwargs
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# Example of combined use
def process_data(name, *args, **kwargs):
    print(f"Processing: {name}")
    print(f"Args: {args}")       # Tuple (10, 20)
    print(f"Kwargs: {kwargs}")     # Dictionary {'city': 'London', 'zip': 'SW1A 0AA'}

# Function calls
print(sum_all(1, 2, 3, 4))             # 10
print_info(name="Alice", age=30, city="New York") # Output key-value info
process_data("Report", 10, 20, city="London", zip="SW1A 0AA")