How do *args and **kwargs work in Python functions?

· Category: Python Programming

Short answer

*args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary. They allow functions to accept any number of arguments.

Steps

  1. Define the function signature with *args and/or **kwargs.
  2. Use args as a tuple and kwargs as a dict inside the function.
  3. Unpack existing collections when calling functions with * and **.
def summarize(prefix, *tags, **metadata):
    print(f"{prefix}: tags={tags}, metadata={metadata}")

summarize("Status", "urgent", "review", author="Alice", priority=1)

Tips

  • You can name them anything, but args and kwargs are conventions.
  • Order matters in signatures: normal args, default args, *args, keyword-only args, **kwargs.
  • Use * alone to force keyword-only arguments: def func(a, *, b): requires b to be passed by name.
# Unpacking
def add(a, b, c):
    return a + b + c

values = [1, 2, 3]
print(add(*values))

config = {"a": 1, "b": 2, "c": 3}
print(add(**config))

Common issues

  • Mixing up * and ** when calling functions raises a TypeError.
  • Duplicate keyword arguments or duplicate keys in **kwargs cause errors.
  • Modifying kwargs directly can affect the caller if the dict is mutable; copy it if needed.