Given the zen of python why is zip(*) used to unzip instead of some function named unzip()? For example Transpose/Unzip Function (inverse of zip)? shows how to unzip a list.
>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
How is that more:
then
>>> unzip([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
?
What am I missing here?
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.
UnZipping in Python Unzipping means converting the zipped values back to the individual self as they were. This is done with the help of “*” operator. So now, if we want to put the old values into listA and listB from zipped list zl, then we have to unzip zl.
Zipping two lists pairs elements from the first list with elements from the second list. For example, zipping [1, 2, 3] and [4, 5, 6] results in [(1, 4), (2, 5), (3, 6)] .
You're not actually unzipping when you do zip(*your_list)
. You're still zipping.
zip
is a function that can take as many arguments as you want. In your case, you essentially have four different sequences that you want to zip: ('a', 1)
, ('b', 2)
, ('c', 3)
and ('d', 4)
. Thus, you want to call zip
like this:
>>> zip(('a', 1), ('b', 2), ('c', 3), ('d', 4))
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
But your sequences aren't in separate variables, you just have a list which contains them all. This is where the *
operator comes in. This operator unpacks the list in a way that each element of your list becomes an argument to the function.
This means that when you do this:
your_list = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
zip(*your_list)
Python calls zip
which each element of your list as an argument, like this:
zip(('a', 1), ('b', 2), ('c', 3), ('d', 4))
This is why an unzip
function isn't necessary: Unzipping is just another kind of zip, and is easily achievable with just the zip
function and the *
operator.
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