OK I love Python's zip()
function. Use it all the time, it's brilliant. Every now and again I want to do the opposite of zip()
, think "I used to know how to do that", then google python unzip, then remember that one uses this magical *
to unzip a zipped list of tuples. Like this:
x = [1,2,3]
y = [4,5,6]
zipped = zip(x,y)
unzipped_x, unzipped_y = zip(*zipped)
unzipped_x
Out[30]: (1, 2, 3)
unzipped_y
Out[31]: (4, 5, 6)
What on earth is going on? What is that magical asterisk doing? Where else can it be applied and what other amazing awesome things in Python are so mysterious and hard to google?
It doesn't always work:
Oops! I think it needs a skull to scare it into working:
In python3 I think you need
since zip now returns a generator function which is not False-y.
The asterisk performs
apply
(as it's known in Lisp and Scheme). Basically, it takes your list, and calls the function with that list's contents as arguments.Addendum to @bcherry's answer:
So it works not just with keyword arguments (in this strict sense), but with named arguments too (aka positional arguments).
The asterisk in Python is documented in the Python tutorial, under Unpacking Argument Lists.
I'm extremely new to Python so this just recently tripped me up, but it had to do more with how the example was presented and what was emphasized.
What gave me problems with understanding the zip example was the asymmetry in the handling of the zip call return value(s). That is, when zip is called the first time, the return value is assigned to a single variable, thereby creating a list reference (containing the created tuple list). In the second call, it's leveraging Python's ability to automatically unpack a list (or collection?) return value into multiple variable references, each reference being the individual tuple. If someone isn't familiar with how that works in Python, it makes it easier to get lost as to what's actually happening.
It's also useful for multiple args:
And, you can use double asterisk for keyword arguments and dictionaries:
And of course, you can combine these:
Pretty neat and useful stuff.