Managing Variable Numbers of Positional Arguments
In this lesson, you will learn how to create flexible functions that accept any number of positional arguments using the *args syntax.
So far, when you define a function, you specify exactly how many arguments it expects. For example, a function defined as def add(a, b): will raise an error if you pass it three numbers. But what if you want to write a function that can add two numbers, three numbers, or even ten numbers at once?
Python provides a special syntax using an asterisk (*) to handle this. By placing an asterisk before a parameter name—typically named *args—you are telling Python to collect all extra positional arguments passed into the function and store them in a single tuple.
How it works
Think of *args as a "catch-all" bucket. When you call the function, Python takes every positional argument you provided and packages them into a tuple, which you can then iterate through just like any other collection.
def sum_all(*args):
total = 0
# args behaves like a tuple containing all the inputs
for number in args:
total += number
return total
# You can now pass any number of arguments!
print(sum_all(1, 2, 3)) # Result: 6
print(sum_all(10, 20)) # Result: 30
print(sum_all(5, 5, 5, 5, 5)) # Result: 25
In the example above, *args allows the function to be completely agnostic about how many numbers it receives. Inside the function, args acts as a tuple: (1, 2, 3) in the first call, and (10, 20) in the second. You can use the accumulator pattern you learned previously to loop through this tuple and process the data regardless of its size.
Keep in mind that args is just the standard convention; the magic is in the * symbol itself. You could technically name it *numbers, and it would work the same way, but *args is the naming convention most Python developers use to signal that a function accepts a variable number of positional inputs.
Key Takeaway: Use the *args syntax in your function definition to collect an arbitrary number of positional arguments into a single tuple for easy processing.