Functions

Args and Kwargs

*args collects extra positional arguments and **kwargs collects named ones.

*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
def f(*args, **kwargs): …→ tuple→ dict
*args captures the extra positionals as a tuple; **kwargs captures the extra keywords as a dict.

**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

See also

Run the complete example

Example code

Expected output

10
{'owner': 'Ada', 'public': True}
scores
(10, 9)
{'owner': 'Ada'}

Execution time appears here after you run the example.