Home › Learn › Python › Functions in depth

*args and **kwargs

Lesson 32 of 40. Accept any number of positional or named arguments.

def total(*nums): collects all positional arguments into a tuple called nums, so total(1, 2, 3) and total() both work. def describe(**info): collects named arguments into a dictionary, so describe(name="Ada", age=36) gives {"name": "Ada", "age": 36}. The names args and kwargs are convention; the stars are the syntax.

The same stars unpack the other way when calling: total(*[1, 2, 3]) spreads a list into separate arguments, and describe(**settings) spreads a dictionary into named ones.

def biggest(*nums):
    return max(nums) if nums else None

print(biggest(3, 9, 2))   # 9

def tag(name, **attrs):
    return name, attrs

print(tag("a", href="/", id="x"))

Your task

Write average(*nums) returning the mean of the numbers, or 0 when none were given, and describe(**info) returning the entries as "key=value" pairs joined by ", ", sorted by key, so describe(name="Ada", age=36) is "age=36, name=Ada".

Hint 1

if not nums: return 0; return sum(nums) / len(nums)

Hint 2

", ".join(f"{k}={v}" for k, v in sorted(info.items()))

Show the solution
def average(*nums):
    if not nums:
        return 0
    return sum(nums) / len(nums)


def describe(**info):
    return ", ".join(f"{k}={v}" for k, v in sorted(info.items()))

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.