Note: Trying to do this in PHP? Check this out.
When declaring a function, the type and number of arguments are usually fixed at compile time. But sometimes it is necessary for a function to be able to accept a variable number of arguments unknown until run-time.
This tutorial will show you how to create a Python function that can accept a variable number of arguments.
In A Nutshell
If you're simply looking for an example to go off of, I won't keep you waiting. Here's an example of a function sum() that adds up all of the integers passed to it and returns the sum:
#!/usr/bin/python def sum(*args): total = 0 for i in args: total += i return total total = sum(1, 2, 3, 4, 5) print "Total: ", total
How It Works
Let's look at the code line by line:
We declare our function. When this function is called, a tuple will be created from the arguments passed to the function, and this tuple will be stored in the variable args.
total = 0
Here we simply create a local variable to hold our return value as we add the individual integers to it.
for i in args: total += i
Here we loop through the list of arguments and add their values to the total. Since tuples are iterable with a simple for-loop, no extra work is needed.
Finally, we return our total.
A Handy Tool: Create A List
One special thing to note is that because the arguments are stored in an immutable tuple, we can convert this tuple to a list using the list() constructor:
arg_list = list(args)
In doing so, we are now able to use list methods such as pop() on our arguments, and we can eliminate the temporary iteration variable i:
while arg_list: total += arg_list.pop()
You should now know how to create a Python function that accepts a variable number of arguments at run-time.
I always welcome questions or feedback about this tutorial. Simply post a reply or PM me; I'm glad to help!
This page was published on