CodeMIRAI
0 XP

*args and **kwargs

2 min read 5 runnable examples Quiz included

Sometimes you don't know in advance how many arguments a function will get. print() is a good example: it accepts any number of values. You can write functions like that too.

*args: any number of positional arguments

A parameter with one star collects all extra positional arguments into a tuple:

Python
def total(*numbers):
    print("Got:", numbers)
    return sum(numbers)

print(total(1, 2))
print(total(5, 10, 15, 20))
print(total())

The name args is just a convention; the star is what matters.

Python
def shout(*words, end="!"):
    return " ".join(w.upper() for w in words) + end

print(shout("hello", "world"))
print(shout("stop", end="."))

**kwargs: any number of keyword arguments

Two stars collect extra keyword arguments into a dictionary:

Python
def make_profile(name, **details):
    print("Name:", name)
    for key, value in details.items():
        print(f"  {key}: {value}")

make_profile("Asha", city="Mumbai", language="Python", level=3)

Using both

The order in a definition is: regular parameters, *args, keyword-only parameters, **kwargs.

Python
def log(level, *messages, sep=" | ", **context):
    line = sep.join(str(m) for m in messages)
    extra = ", ".join(f"{k}={v}" for k, v in context.items())
    print(f"[{level}] {line}" + (f"  ({extra})" if extra else ""))

log("INFO", "server started", "port 8080")
log("ERROR", "payment failed", user="asha", amount=499)

Unpacking into a call

The stars also work the other way: in a call, * spreads a list or tuple into separate positional arguments, and ** spreads a dictionary into keyword arguments.

Python
def describe(name, age, city):
    print(f"{name}, {age}, from {city}")

person_list = ["Leo", 30, "London"]
person_dict = {"name": "Mei", "age": 24, "city": "Osaka"}

describe(*person_list)
describe(**person_dict)

numbers = [3, 1, 4, 1, 5]
print(max(*numbers), min(numbers))
print(*numbers, sep=" < ")
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.