-1

The official Python3 Documents said:

zip() in conjunction with the * operator can be used to unzip a list:

But also said, the zip() is "Make an iterator that aggregates elements from each of the iterables"

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
list(zipped)

x2, y2 = zip(*zip(x, y))

I'm confused with the last line zip(*zip(x, y)), the zip(x, y) returns a iterable object, not a list. How can *zip(x, y) works!? How can *upzip an iterator!?

Lochu'an Chang
  • 111
  • 1
  • 4
  • 1
    Why do you think `*` cannot unpack an iterator? It may simply call `next()` until iterator is exhausted – Łukasz Rogalski Nov 08 '16 at 15:41
  • 1
    Possible duplicate of [What does asterisk \* mean in Python?](http://stackoverflow.com/questions/400739/what-does-asterisk-mean-in-python) – Eli Sadoff Nov 08 '16 at 15:42

1 Answers1

1

This is what happens in the last statement. The inner zip:

zip(x, y) 

...results in an iterable over ([1,4], [2,5], [3,6]). Then this:

zip(*zip(x, y))

translates to:

zip([1,4], [2,5], [3,6])

... because the asterisk consumes the iterable and spreads the values so they become individual arguments to the outer zip function.

That expression is than evaluated to an iterable over two values:

([1, 2, 3], [4, 5, 6])

... which needs to get assigned (unpacked) to two variables (x2 and y2 respectively), and so for that reason these two values are consumed from the iterable.

trincot
  • 317,000
  • 35
  • 244
  • 286