0

I am reading Learning Python and am having a hard time understanding what exactly the author is trying to convey here.

He says: because argument-unpacking syntax in calls accepts iterables, it's also possible to use the zip built in call to unzip zipped tuples, by making prior or nested zip results arguments for another zip call.

>>> X = (1, 2)
>>> Y = (3, 4)
>>> list(zip(X, Y))
[(1, 3), (2, 4)] # Zip tuples; returns an iterable.
>>> A, B = zip(*zip(X, Y)) # Unzip a zip! 
>>> A
(1, 2)
>>> B
(3, 4)

I do not understand the point of the zip and then *zip? Wouldn't A, B = X, Y do the same thing. Can someone help explain this concept for me?

  • It's not a useful thing, really. The author's just playing around to demonstrate concepts. – John Kugelman Aug 06 '18 at 00:20
  • I guess I'm confused slightly on zip and iterables. I'm not seeing the importance of them at this point on a pragmatic level. Is there anything important about knowing these topics? – Brandon Lewallen Aug 06 '18 at 00:35
  • 1
    Iteration is something you'll be doing constantly. You'll need that knowledge to build an understanding of concepts like generators, which are very important. `zip` isn't critical knowledge, but it is a useful tool. There are also some neat tricks you can do with it. Try `zip(*[iter(range(15))]*3)`, and try working out what's going on under the hood. – Patrick Haugh Aug 06 '18 at 01:07
  • Let me know if I am understanding your example. It would appear that it is creating tuples of 3 up to, but not including, the number 15. It makes sense from a reverse engineering standpoint, but I guess I am not understanding why that specific syntax works that way. Why does multiplying by three at the end create groups? – Brandon Lewallen Aug 06 '18 at 01:13
  • He does mention that in chapter 18 we will go over the *args in more depth. I think that this is what is causing my confusion on it. Like, it makes sense, but I guess this piece of information, or lack thereof, is making it more confusing than what it probably is. – Brandon Lewallen Aug 06 '18 at 01:20
  • @BrandonLewallen It's more sophisticated than that. You are basically creating 3 references to the same iterator. See [this answer](https://stackoverflow.com/a/23286299/2011147) for details. – Selcuk Aug 06 '18 at 01:57
  • The first `zip` regroups the elements of `X` and `Y`. The 2nd `zip` shows that the shuffling can be reversed. In matrix terms this a kind of `transpose`. – hpaulj Aug 06 '18 at 02:43

0 Answers0