*args (variable arguments)
A parameter with * in a definition collects all extra positional arguments into a tuple.
Used in 18 lessons of the course, from 01.01.
In def f(*args), the * tells Python: "gather every positional argument that arrives into one tuple". Inside the function, args is a regular tuple. You can loop over it with for, ask for its len(), or index it.
The name args is only a convention. The * is what matters. That is why the course has def compare_defaults(*classes): the function accepts any number of classes, and inside, classes is a tuple holding all of them.
It is written this way so the caller does not have to build a list first: f(1, 2, 3) works just like f(1) or f(). If you pass nothing, you get an empty tuple.
def total(*nums):
return sum(nums)
Reach for it when: a function should accept an open-ended number of values of the same kind, such as several classes or several numbers.
Examples
Common mistake
def add(*nums):
return sum(nums)
print(add([1, 2, 3]))Why: The whole list arrives as one single argument, so `nums` is `([1, 2, 3],)` and `sum` tries to add 0 + a list.
How to write it: Unpack the list in the call: add(*[1, 2, 3]), or pass the values separately.
