← All lessons

*args: any number of arguments

Sign in · Sign up

Lesson 6.4

Sometimes you don't know in advance how many arguments there will be. *args collects them all into a tuple:

def total(*args):
    result = 0
    for x in args:
        ...                 # add x
    return result

The star before the name matters: without it the function takes exactly one argument. Inside, args is an ordinary tuple, and you can loop over it.

Write a function total(*args) that returns the sum of all the numbers passed in. With no arguments the sum is 0.

Hint

A parameter with a star collects all the positional arguments into a tuple.

Inside — a loop over that tuple and adding to the sum. You write one star: def total(*args), and call it as usual: total(1, 2, 3).