Lesson 7 of 19 · 2 min
*args — Accept Any Number of Positional Arguments
What if you want a function that can add 2 numbers or 10 numbers with the same code? *args collects any number of extra positional arguments into a tuple. The asterisk * is the magic; args is just the conventional name.
def add_all(*numbers): # *numbers = everything passed, as a tuple
print(f"Received tuple: {numbers}") # show what came in
total = 0 # start accumulator at zero
for num in numbers: # iterate over the tuple
total += num # add each number to running total
return total # return final sum
print(add_all(1, 2, 3)) # 3 arguments
print(add_all(10, 20, 30, 40)) # 4 arguments — same function handles both!
print(add_all(5)) # 1 argument — still works
Output: Received tuple: (1, 2, 3) 6 Received tuple: (10, 20, 30, 40) 100 Received tuple: (5,) 5
