Python *args & **kwargs
In this page:
What is *args?
*args lets a function accept any number of positional arguments beyond its named parameters, collecting them into a tuple inside the function — useful when you don't know in advance how many values the caller will pass.
Example: What is *args?
def total(*args):
print(args)
return sum(args)
print(total(1, 2, 3))
What is **kwargs?
**kwargs does the same job for keyword arguments, collecting any extras into a dictionary mapping parameter names to values — commonly used to forward arbitrary options through to another function without listing each one explicitly.
Example: What is **kwargs?
def show(**kwargs):
print(kwargs)
show(name="Alex", age=30)
Mixing Standard Parameters with *args
You can define ordinary named parameters before *args in the same function; any positional arguments beyond what those named parameters consume simply overflow into the *args tuple automatically.
Example: Mixing Standard Parameters with *args
def greet(greeting, *names):
for name in names:
print(greeting, name)
greet("Hi", "Alex", "Sam")
Mixing *args and **kwargs
When combining both in one definition, Python requires a strict order: standard parameters first, then *args, then **kwargs — this ordering is enforced by the language, not just a style convention.
Example: Mixing *args and **kwargs
def info(id, *args, **kwargs):
print(id, args, kwargs)
info(1, "extra", city="NYC")
Unpacking with * and **
The * and ** operators also work in reverse at a call site: *a_list unpacks a list's items into separate positional arguments, and **a_dict unpacks a dictionary's items into keyword arguments for the call.
Example: Unpacking with * and **
def add(a, b, c):
return a + b + c
values = [1, 2, 3]
print(add(*values))
data = {"a": 1, "b": 2, "c": 3}
print(add(**data))
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: