Unpack Function Arguments with * and **
Core idea
At a call site, *values expands an iterable (such as a list or tuple) into positional arguments. **options expands a mapping with string keys into named arguments. This is the reverse direction of gathering arguments in a definition.
def area(width, height): return width * height
size = [4, 6]print(area(*size))The list supplies two positional arguments.
Expand named settings
def charge(price, fee): return price + fee
settings = {"fee": 2, "price": 9}print(charge(**settings))The dictionary keys match parameter names, independent of their order.
Duplicate binding (intentional error)
def charge(price, fee): return price + fee
charge(9, **{"price": 4, "fee": 2})Price receives two values, so the call is rejected.
Common mistake
Calling area(size) supplies one list, not two arguments. ** requires a mapping with string keys; unknown names are rejected unless the function accepts them with **kwargs.
Practice
Create a function taking width and height, then call it using a tuple and a dictionary. Compare the results.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Argument unpacking
Check your understanding of argument unpacking.
What is printed?
def f(a, b): return a * bprint(f(*[2, 7]))What is printed?
def f(a, b): return a - bprint(f(**{"b": 2, "a": 5}))What happens?
def f(a): return af(2, **{"a": 7})What does **mapping supply in a call?