Any number of arguments: *args
🌍 In real life. A shopkeeper adds up whatever you put on the counter: one item, five items, or none. They don't need to know in advance how many; they just total the pile. And when you order "rice, plus egg and dal", the first item is the main dish and everything after it is extras.
A starred parameter lets a function take a pile of any size like that.
The idea in one sentence: a parameter like *nums collects all the extra positional arguments into a tuple, so a function can take any number of them, even none.
Its words:
*args: a starred parameter;argsis the usual name, but any name works- extra positional arguments: values left over after the normal parameters are filled
- unpacking in a call:
f(*my_list)spreads a list into separate arguments
Step by step, for order("rice", "egg", "dal") with def order(food, *extras)::
foodtakes the first value,"rice".*extrascollects everything left, as a tuple:("egg", "dal").- With just
order("bread"),extrasis the empty tuple().
def total(*nums):
return sum(nums)
print(total(1, 2, 3))
print(total(10))
print(total())Normal parameters come first and take their values first; the starred one collects whatever is left:
def order(food, *extras):
print("Main:", food)
print("Extras:", extras)
order("rice", "egg", "dal")
order("bread")The star works the other way round in a call: *my_list spreads a list out into separate arguments.
def total(*nums):
return sum(nums)
scores = [4, 5, 6]
print(total(*scores))
print(max(*scores))How Python does it. The normal parameters are filled first, from the left; whatever is left over is packed into one tuple. The star in a call does the reverse: it unpacks a list into separate values before the call starts. print(*words) is a neat example: each word becomes its own argument, so print puts spaces between them.
Mistakes and edge cases.
- Passing a list without the star.
total([1, 2])givesnumsa tuple holding one item, the list:([1, 2],). Writetotal(*[1, 2]). - A star on something you can't loop over.
total(*5)stops with a TypeError: the value after*must be a list, tuple or other sequence. - Two starred parameters.
def f(*a, *b):givesSyntaxError: * argument may appear only once. - Forgetting it's a tuple. You can loop over
argsand uselen(args), but you can'tappendto it.
Quiz
What does this print?
def count(*things): return len(things) print(count("a", "b", "c"), count())What does this print?
def show(first, *rest): print(first, rest) show(1, 2, 3)What does this print?
def add(a, b): return a + b pair = [3, 4] print(add(*pair))What type of value does
*argshold inside the function?- A tuple
- A list
- A dictionary
Which line has a mistake?
def total(*nums): return sum(nums) print(total([1, 2, 3]))
Coding tasks
Write
total(*nums)that returns the sum of all its arguments (0 when there are none).Write
biggest(first, *rest)that returns the largest of all its arguments. It always gets at least one.Write
join_words(*words, sep=" ")that returns all the words joined bysep.