Python: why is zip(*) used instead of unzip()? -


given zen of python why zip(*) used unzip instead of function named unzip()? example transpose/unzip function (inverse of zip)? shows how unzip list.

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

how more:

  • beautiful ugly
  • explicit implicit
  • simple complex
  • readable
  • etc.

then

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

?

what missing here?

you're not unzipping when zip(*your_list). you're still zipping.

zip function can take many arguments want. in case, have 4 different sequences want zip: ('a', 1), ('b', 2), ('c', 3) , ('d', 4). thus, want call zip this:

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

but sequences aren't in separate variables, have list contains them all. * operator comes in. operator unpacks list in way each element of list becomes argument function.

this means when this:

your_list = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] zip(*your_list) 

python calls zip each element of list argument, this:

zip(('a', 1), ('b', 2), ('c', 3), ('d', 4)) 

this why unzip function isn't necessary: unzipping kind of zip, , achievable zip function , * operator.


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

css - Can I use the :after pseudo-element on an input field? -