What does the star operator * do in Python when used as an argument in functions like zip(*x)
or fcn(**k)
?
- How does the interpreter handle it internally?
- Does it affect performance? Is it fast or slow?
- When is it useful and where is it not?
- Should I use it when defining a function or when calling it?
The star
*
unpacks a sequence/collection into positional arguments, and can be used when calling a function:This unpacks the tuple; what is finally executed is:
The double star
**
does the same thing, but with named dictionaries and arguments:This takes the dictionary and converts it to a series of
llave=valor
. The result is the execution of:Star and double star can be combined:
will run as:
It can also be applied to generators:
and inside tuples, lists and dictionaries:
In the definition of a function
In addition, functions can be defined with arguments of type
*x
and**y
. This allows the function to accept any number of positional arguments and/or named arguments, without having to specifically individualize them.Example:
Also using
**
:so you can indicate a large number of optional arguments without having to declare them.
They can also be combined:
quick reference
Dices
then
References:
4.7.5. Unpacking an argument list
PEP 448 -- Additional Unpacking Generalizations