Back to course

Arbitrary Arguments: `*args` (Positional)

Python Programming: The 0 to Hero Bootcamp

Arbitrary Positional Arguments (*args)

Sometimes you need a function that can accept an unknown or variable number of positional arguments (e.g., a function that sums all numbers passed to it).

Python handles this using *args.

Usage

When *args is used as a parameter, all extra positional arguments passed to the function are collected into a tuple named args.

python def calculate_sum(*numbers): # 'numbers' is a tuple containing all passed arguments total = 0 for n in numbers: total += n return total

Call 1: 3 arguments

print(calculate_sum(1, 2, 3)) # Output: 6

Call 2: 5 arguments

print(calculate_sum(10, 20, 30, 40, 50)) # Output: 150

Call 3: 0 arguments

print(calculate_sum()) # Output: 0

Combining with Positional Args

If you use both regular parameters and *args, the regular parameters take the first arguments, and *args collects the rest.

python def summarize(title, *items): print(f"--- {title} ---") for item in items: print(f"- {item}")

summarize("Shopping List", 'Milk', 'Bread', 'Eggs')