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?
Python's zip() function is defined as zip(*iterables) . The function takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.
The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.
Basically, it passes the contents of the lists as arguments.
The zip() function returns an iterator of tuples based on the iterable objects. If a single iterable is passed, zip() returns an iterator of tuples with each tuple having only one element. If multiple iterables are passed, zip() returns an iterator of tuples with each tuple having elements from all the iterables.
The asterisk in Python is documented in the Python tutorial, under Unpacking Argument Lists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With