← Back to Python Course | Chapter 4: Functions | Lesson 5 of 9

Python *args & **kwargs

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?

python
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?

python
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

python
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

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

python
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))

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.