Collect Arguments with *args and **kwargs
Core idea
In a definition, *args gathers extra positional arguments into a tuple, and **kwargs gathers extra keyword arguments into a dictionary. The names args and kwargs are conventions; the stars give them their meaning. A call may supply no extra arguments.
def total(*readings): result = 0 for value in readings: result += value return result
print(total(2, 4, 6))print(total())The readings tuple has three elements in the first call and is empty in the second.
Collect named options
def options(**settings): return settings
print(options(color="blue", size=2))The names become dictionary keys.
Combine named and extra arguments
def report(label, *values, **details): print(label) print(values) print(details)
report("A", 3, 5, unit="cm")Label has its own slot; values and details capture the remaining arguments.
Common mistake
*args is a tuple, not a list, so it has no append method. **kwargs does not collect positional values. Ordinary named parameters still bind first.
Practice
Define a function that counts the extra positional and keyword arguments. Try it with no arguments, two readings and a named unit.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Variable argument collection
Check your understanding of args and kwargs.
What is printed?
def f(*values): print(values)f(2, 3)What is printed?
def f(**options): print(options)f(size=4)What is printed?
def f(*args): return len(args)print(f())Which part of *values gives it its collection behavior?