Chapter 4: More functions

Arbitrary number of function arguments

face Josiah Wang

So far, when using functions, we have assumed a fixed number of parameters in the function definition. You then call these functions via either positional arguments and/or keyword arguments.

Sometimes, you may not know upfront how many arguments will be provided by the caller. For example, you might have noticed that you can call the built-in max() function with as many arguments as needed: max(1, 5, 10, 8, 2, 3).

How do you achieve this in Python? You use an asterisk (*) before the parameter name. Python will pack the parameters into a tuple and assign it to your parameter.

def enroll(*courses): 
    print(type(courses))  # <class 'tuple'>
    for course in courses: 
        print(course)

enroll("Probabilistic Inference", "Introduction to Machine Learning",
    "Computer Vision", "Graphics")

Think of it as packing individual items into a bag (tuple)!