In code like zip(*x) or f(**k), what do the * and ** respectively mean? How does Python implement that behaviour, and what are the performance implications?
See also: Expanding tuples into arguments. Please use that one to close questions where OP needs to use * on an argument and doesn’t know it exists. Similarly, use Converting Python dict to kwargs? for the case of using **.
See What does ** (double star/asterisk) and * (star/asterisk) do for parameters? for the complementary question about parameters.
A single star
*unpacks a sequence or collection into positional arguments. Suppose we haveUsing the
*unpacking operator, we can writes = add(*values), which will be equivalent to writings = add(1, 2).The double star
**does the same thing for a dictionary, providing values for named arguments:Both operators can be used for the same function call. For example, given:
then
s = add(*values1, **values2)is equivalent tos = sum(1, 2, c=10, d=15).See also the relevant section of the tutorial in the Python documentation.
Similarly,
*and**can be used for parameters. Using*allows a function to accept any number of positional arguments, which will be collected into a single parameter:Now when the function is called like
s = add(1, 2, 3, 4, 5),valueswill be the tuple(1, 2, 3, 4, 5)(which, of course, produces the result15).Similarly, a parameter marked with
**will receive adict:this allows for specifying a large number of optional parameters without having to declare them.
Again, both can be combined: