*args & **kwargs
Accept any number of positional or keyword arguments.
Syntax
def f(*args, **kwargs):
...Sometimes a function should accept a flexible number of arguments.
*argscollects extra positional arguments into a tuple.**kwargscollects extra keyword arguments into a dictionary.
The names args and kwargs are only a convention — the * and ** are what matter.
Example
def total(*args):
return sum(args)
print(total(1, 2, 3, 4))
def describe(**kwargs):
for key, value in kwargs.items():
print(f'{key}: {value}')
describe(name='Ada', age=36)
# Output:
# 10
# name: Ada
# age: 36When to use it
- A logging helper accepts *args to print any number of values on one line without a fixed count.
- A database query builder uses **kwargs to accept optional WHERE clause fields as keyword arguments.
- A decorator passes *args and **kwargs through to the wrapped function without knowing its signature.
More examples
*args for variable positional arguments
Uses *args to accept any number of positional price values and sums them.
def total(*prices):
return sum(prices)
print(total(10, 20)) # 30
print(total(5, 15, 25, 35)) # 80**kwargs for keyword arguments
Collects any keyword arguments into a dict and iterates over them to display a profile.
def build_profile(**info):
for key, val in info.items():
print(f'{key}: {val}')
build_profile(name='Alice', role='admin', active=True)
# Output:
# name: Alice
# role: admin
# active: TrueCombine positional, *args, and **kwargs
Uses all three forms together: a required positional arg, *args for items, and **kwargs for metadata.
def report(title, *items, **meta):
print(f'--- {title} ---')
for item in items:
print(' -', item)
for k, v in meta.items():
print(f' [{k}={v}]')
report('Sales', 'Laptops', 'Phones', year=2024, region='EU')
# --- Sales ---
# - Laptops
# - Phones
# [year=2024]
# [region=EU]
Discussion