5

I wanted to learn the functionalities of the zip class. I wrote this very simple example.

>>> names = ['name1','name2','name3']
>>> ages = ['age1','age2','age3']
>>> print(zip(names, ages))
<zip object at 0x03DB18F0>
>>> zipped = zip(names, ages)
for i in zipped:
    type(i)
    print(i)

and the output is (as expected) -

<class 'tuple'>
('name1', 'age1')
<class 'tuple'>
('name2', 'age2')
<class 'tuple'>
('name3', 'age3')

However immediately after this line if i write:

for i in zipped:
    print(i)

it compiles but prints nothing!

To recheck I did this again -

>>> zipped = zip(names, ages)
>>> for i in zipped:
    print(i)
('name1', 'age1')
('name2', 'age2')
('name3', 'age3')

This time it prints correctly. But while doing unzip -

>>> names2, ages2 = zip(*zipped)
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    names2, ages2 = zip(*zipped)
ValueError: not enough values to unpack (expected 2, got 0)

It seems the zipped variable becomes empty for some reason?

Note: if required you may change the title of the question. I am using python 3.6.1 on a windows (10) machine.

Chen A.
  • 10,140
  • 3
  • 42
  • 61
Arjee
  • 372
  • 3
  • 15

2 Answers2

14

zip produces an iterator (<zip object at 0x03DB18F0>) which can only be iterated once. Once you have iterated it, it's exhausted. If you want to produce a list which can be iterated as often as you like:

zipped = list(zip(names, ages))
deceze
  • 510,633
  • 85
  • 743
  • 889
  • Excellent. Thank you so much. that was the only guess that I was having :) it sounds like how a generator works. is it same/similar implementation? – Arjee Oct 30 '17 at 08:37
  • 1
    @Arjee generators are a language construct that was introduced to make writing iterators easier, but not all iterators are generators, and now generators have been used for other things, as co-routines for example. – juanpa.arrivillaga Oct 30 '17 at 08:47
  • 1
    @Arjee see [this](https://stackoverflow.com/questions/2776829/difference-between-pythons-generators-and-iterators) question. – juanpa.arrivillaga Oct 30 '17 at 08:48
4

This is because zip returns an iterator object. They can't be iterated more than once, then they become exhausted.

You can create a list out of your iterator using list(zip(names, ages)).

The list uses the iterator object to create a list, which can be iterated multiple times.

You can read more about the zip function here.

Chen A.
  • 10,140
  • 3
  • 42
  • 61