Functions
Args and Kwargs
*args collects extra positional arguments into a tuple. This fits functions that naturally accept any number of similar values.
Source
def total(*numbers):
return sum(numbers)
print(total(2, 3, 5))Output
10**kwargs collects named arguments into a dictionary. The names become string keys.
Source
def describe(**metadata):
print(metadata)
describe(owner="Ada", public=True)Output
{'owner': 'Ada', 'public': True}A function can combine explicit parameters, *args, and **kwargs. Put the flexible parts last so the fixed shape remains visible.
Source
def report(title, *items, **metadata):
print(title)
print(items)
print(metadata)
report("scores", 10, 9, owner="Ada")Output
scores
(10, 9)
{'owner': 'Ada'}Notes
- Use these tools when a function naturally accepts a flexible shape.
- Prefer explicit parameters when the accepted arguments are known and fixed.
*argsis a tuple;**kwargsis a dictionary.
See also
- related: Functions
- related: Keyword-only Arguments
- related: Partial Functions
- next depth: ParamSpec
Run the complete example
Expected output
10
{'owner': 'Ada', 'public': True}
scores
(10, 9)
{'owner': 'Ada'}
Execution time appears here after you run the example.