Chapter 7: Functions

Arbitrary number of positional arguments

face Josiah Wang

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)!