>A Byte of Python

Receiving Tuples and Lists in Functions

There is a special way of receiving parameters to a function as a tuple or a dictionary using the * or ** prefix to the parameter name respectively. This is useful for receiving a variable number of arguments in a function.

>>> def sum(number, *args):
...     '''Return the sum the number of args.'''
...     total = 0
...     for i in range(0, number):
...             total += args[i]
...     return total
...
>>> sum(3, 10, 20, 30)
60
>>> sum(2, -5, -10)
-15
>>>
      

Due to the * prefix on the args variable, all the extra arguments passed to the function are stored in args as a tuple. If a ** prefix had been used instead, the extra parameters would have been stored in a dictionary.