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
- Define the function signature with
*argsand/or**kwargs. - Use
argsas a tuple andkwargsas a dict inside the function. - 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
argsandkwargsare 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):requiresbto 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 aTypeError. - Duplicate keyword arguments or duplicate keys in
**kwargscause errors. - Modifying
kwargsdirectly can affect the caller if the dict is mutable; copy it if needed.