In this Python article we want to learn How to Pass Arbitrary Number of Arguments in Python,
Sometimes you won’t know ahead of time how many arguments a function needs to accept.
fortunately, Python allows a function to collect an arbitrary number of arguments from the
calling statement. For example, consider a function that print numbers. It needs to accept
number , but you can’t know ahead of time how many numbers will be added for printing.
the function in the following example has one parameter, *numbers, but this parameter
collects as many arguments as the calling line provides. you can use asterisks for doing this.
1 2 3 4 |
def add(*numbers): print(numbers) add(1,2,3,4,5,6,7,8,9) |
The asterisk in the parameter name *numbers tells Python to make an empty tuple
called numbers and pack whatever values it receives into this tuple. The print() call
in the function body produces output showing that Python can handle a function call
with one value and a call with different values. It treats the different calls similarly.
Note that Python packs the arguments into a tuple, even if the function receives only
one value:
Run the code and this is the result.
- TKinter Tutorial For Beginners
- PyQt5 Tutorial For Beginners
- Python MySQL Database
- Python SQLite Database
Now we can replace the print() call with a loop that runs through the list of numbers
and describes the numbers being printed.
1 2 3 4 5 |
def add(*numbers): for number in numbers: print(number) add(1,2,3,4,5,6,7,8,9) |
If you run the code you will see all numbers, but this time it is not in tuple.