How to Pass Arbitrary Number of Arguments in Python

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.

 

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.

How to Pass Arbitrary Number of Arguments in Python
How to Pass Arbitrary Number of Arguments in Python

 

 

 

 

Now we can replace the print() call with a loop that runs through the list of numbers

and describes the numbers being printed.

 

 

If you run the code you will see all numbers, but this time it is not in tuple.

 

 

 

Leave a Comment