TheA single star *
unpacks thea sequence/collection or collection into positional arguments, so you can do this:. Suppose we have
def sumadd(a, b):
return a + b
values = (1, 2)
s = sum(*values)
This will unpackUsing the tuple so that it actually executes as:*
unpacking operator, we can write s = add(*values)
, which will be equivalent to writing s = add(1, 2)
.
s = sum(1, 2)
The double star **
does the same, only using thing for a dictionary and thus, providing values for named arguments:
values = { 'a': 1, 'b': 2 }
s = sumadd(**values) # equivalent to add(a=1, b=2)
YouBoth operators can also combinebe used for the same function call. For example, given:
def sum(a, b, c, d):
return a + b + c + d
values1 = (1, 2)
values2 = { 'c': 10, 'd': 15 }
s = sum(*values1, **values2)
will execute as:then s = add(*values1, **values2)
is equivalent to s = sum(1, 2, c=10, d=15)
.
s = sum(1, 2, c=10, d=15)
Also see sectionSee also the 4.7.4 - Unpacking Argument Listsrelevant section of the tutorial in the Python documentation.
Additionally you can define functions to takeSimilarly, *x*
and **y**
arguments, thiscan be used for parameters. Using *
allows a function to accept any number of positional and/or named arguments that aren't specifically named in the declaration.
Example, which will be collected into a single parameter:
def sumadd(*values):
s = 0
for v in values:
s = s + v
return s
s = sum(1, 2, 3, 4, 5)
orNow when the function is called like s = add(1, 2, 3, 4, 5)
, values
will be the tuple (1, 2, 3, 4, 5)
(which, of course, produces the result 15
).
Similarly, a parameter marked with **
will receive a dict
:
this can allow you to specifyallows for specifying a large number of optional parameters without having to declare them.
And againAgain, youboth can combinebe combined:
def sumadd(*values, **options):
s = 0
for i in values:
s = s + i
if "neg" in options:
if options["neg"]:
s = -s
return s
s = sumadd(1, 2, 3, 4, 5) # returns 15
s = sumadd(1, 2, 3, 4, 5, neg=True) # returns -15
s = sumadd(1, 2, 3, 4, 5, neg=False) # returns 15