What does the *
operator mean in Python, such as in code like zip(*x)
or f(**k)
?
In a function call the single star turns a list into seperate arguments (e.g. zip(*x)
is the same as zip(x1,x2,x3)
if x=[x1,x2,x3]
) and the double star turns a dictionary into seperate keyword arguments (e.g. f(**k)
is the same as f(x=my_x, y=my_y)
if k = {'x':my_x, 'y':my_y}
.
In a function definition it's the other way around: the single star turns an arbitrary number of arguments into a list, and the double start turns an arbitrary number of keyword arguments into a dictionary. E.g. def foo(*x)
means "foo takes an arbitrary number of arguments and they will be accessible through the list x (i.e. if the user calls foo(1,2,3)
, x
will be [1,2,3]
)" and def bar(**k)
means "bar takes an arbitrary number of keyword arguments and they will be accessible through the dictionary k (i.e. if the user calls bar(x=42, y=23)
, k
will be {'x': 42, 'y': 23}
)".