3

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) 
print(list(numbers_letters))

As expected you see the list containing the tuples:

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

But now:

print(list(numbers_letters))

returns an empty list. Where did my data go?

eric
  • 7,142
  • 12
  • 72
  • 138

2 Answers2

2

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

By doing:

print(list(numbers_letters))

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

Dipen Dadhaniya
  • 4,550
  • 2
  • 16
  • 24
2

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.

Yash
  • 3,438
  • 2
  • 17
  • 33
  • There no way to reset it to start at the beginning again? – eric Oct 09 '19 at 13:25
  • Nope. That's just not how it works. You'll need to call zip() again or store the iterator and make copies of it – Yash Oct 09 '19 at 13:28