Inspecting zipped data seems to erase it


When I inspect my zipped data, it acts as if it has been erased. First, create zip object:

numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
numbers_letters = zip(numbers, letters) 

As expected you see the list containing the tuples:

[(1, 'a'), (2, 'b'), (3, 'c')]

But now:


returns an empty list. Where did my data go?

Asked By: eric



Iterators are designed to generate data on the fly exactly one time, no more.

By doing:


For the first time, you have exhausted the iterator. So, the second time there is nothing left to iterate!

Answered By: Dipen Dadhaniya

This is because zip returns an iterator in Python3.x. You can only iterate over an iterator once.

I suggest using:

print(list(zip(numbers, letters)))

In simple terms, considering you have knowledge about pointers to
nodes in a linked list(C, C++), once you traverse through the list
using the head pointer, you can’t use it again to start from the head.

Answered By: Yash
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.