Python *args and **kwargs Explained With Examples
Understand Python *args and **kwargs, how they collect function arguments, and how one or two asterisks unpack lists and dictionaries in calls.
In a Python function definition, *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary.
def describe(*args, **kwargs):
print(args)
print(kwargs)
describe("Python", "Sheets", level="beginner")
# ('Python', 'Sheets')
# {'level': 'beginner'}
The names args and kwargs are conventions. The asterisks create the special behaviour.
Use *args for extra positional arguments
def total(*numbers):
return sum(numbers)
print(total(10, 20, 30)) # 60
Inside the function, numbers is the tuple (10, 20, 30).
Use **kwargs for extra named arguments
def build_profile(name, **details):
return {"name": name, **details}
profile = build_profile("Ryan", role="author", active=True)
Inside the function, details is a dictionary containing role and active.
Combine ordinary parameters, *args and **kwargs
The usual order is:
def example(required, *args, option=True, **kwargs):
pass
requiredis an ordinary positional or keyword argument.argscollects extra positional arguments.optionis keyword-only because it appears after*args.kwargscollects remaining keyword arguments.
Unpack a sequence when calling a function
One asterisk also expands an iterable into positional arguments:
values = [4, 7]
print(pow(*values)) # same as pow(4, 7)
The number of expanded values must fit the function’s parameters.
Unpack a dictionary when calling a function
Two asterisks expand dictionary keys into keyword argument names:
options = {"sep": " | ", "end": "\n"}
print("Python", "Sheets", **options)
Dictionary keys must be strings that match accepted parameter names.
Merge dictionaries with **
defaults = {"theme": "light", "page_size": 20}
custom = {"theme": "dark"}
settings = {**defaults, **custom}
# {'theme': 'dark', 'page_size': 20}
Later values replace earlier values with the same key.
Common mistakes
argsis a tuple, not a list.kwargsis a dictionary.- A function can have only one
*argscollector and one**kwargscollector. - Put
**kwargsafter all other parameters. - Do not use flexible arguments merely to avoid designing a clear function signature.
For the wider meaning of starred expressions, see what an asterisk before a Python variable means and the double-asterisk operator.