Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

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 respectively. This is useful when taking variable number of arguments in the function.

>>> def powersum(power, *args):
... '''Return the sum of each argument raised to specified power.''' ... total = 0
... for i in args:
... total += pow(i, power)
... return total
...
>>> powersum(2, 3, 4)
25

>>> powersum(2, 10) 100

Due to the * prefix on theargs variable, all extra arguments passed to the function are stored inargs as a tuple. If a** prefix had been used instead, the extra parameters would be considered to be key/ value pairs of a dictionary.