Hone

Lessons · Python · *args

A function that takes any number of values

def f(*args) collects every positional argument into a tuple, so f(1), f(1, 2, 3) and f() all work.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

print takes any number of things; so do max, logging helpers, and most 'combine these' functions you will write.

How to think about it

Ask: is the number of inputs fixed? If not, use *args and treat it as a tuple inside. To pass a list INTO such a function, unpack it with a star: f(*my_list).

Worked example

def biggest(*nums):
nums is a tuple of whatever was passed.
    return max(nums) if nums else None
Handle the empty call.
print(biggest(4, 9, 2))
9.
print(biggest(*[1, 5]))
5: the star unpacks the list into arguments.

Your turn

Accept any number of names and greet them all.

def greet(names):
    for n in names:
        print("hi", n)

The trap

Forgetting the star when calling with a list: biggest([4, 9]) passes one argument, a list, and max of one list is that list.

Practise *args on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.