Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: why is zip(*) used instead of unzip()? [closed]

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:

  • Beautiful than ugly
  • Explicit than implicit
  • Simple than complex
  • Readable
  • etc.

then

>>> unzip([('a', 1), ('b', 2), ('c', 3), ('d', 4)])

?

What am I missing here?

like image 512
SpeedCoder5 Avatar asked Jan 07 '16 15:01

SpeedCoder5


People also ask

What does zip (*) do in Python?

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.

Is there an unzip function in Python?

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.

What happens when you zip two lists in Python?

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)] .


1 Answers

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.

like image 122
Vincent Savard Avatar answered Sep 27 '22 21:09

Vincent Savard