| An Introduction to Python by Guido van Rossum and Fred L. Drake, Jr. Paperback (6"x9"), 124 pages ISBN 0954161769 RRP £12.95 ($19.95) Sales of this book support the Python Software Foundation! Get a printed copy>>> |
4.7.4 Unpacking Argument Lists
The reverse situation occurs when the arguments are already in a list
or tuple but need to be unpacked for a function call requiring separate
positional arguments. For instance, the built-in range()
function expects separate start and stop arguments. If they
are not available separately, write the function call with the
*-operator to unpack the arguments out of a list or tuple:
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from list
[3, 4, 5]
In the same fashion, dictionaries can deliver keyword arguments with the
**-operator:
>>> def parrot(voltage, state='a stiff', action='voom'):
... print "-- This parrot wouldn't", action,
... print "if you put", voltage, "volts through it.",
... print "E's", state, "!"
...
>>> d = {"voltage": "four million",
"state": "bleedin' demised",
"action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million
volts through it. E's bleedin' demised !
| ISBN 0954161769 | An Introduction to Python | See the print edition |