0

I was working on a project when I came into this really weird bug, and I have managed to cut it down to this:

xr = zip(range(0, 5), range(0, 5))
yr = zip(range(3, 4), range(0, 1))

print(list(xr), list(yr))
print(list(xr))

The expected output would be this:

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] [(3, 0)]
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

Because I don't change xr or yr after I set them. I am just printing them as a list to the shell. But, when I actually run it, I get this output:

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] [(3, 0)]
[]

I have absolutely no clue why. I have been using python for about a week, and maybe this is supposed to happen, but I would appreciate it if someone told me what's going on here. Thanks!

My python version is Python 3.8.3

oriont
  • 684
  • 2
  • 10
  • 25

2 Answers2

3

The zip function creates an iterator object, which can only be consumed once. This post explains why you cannot iterate over data twice.

This document explains the iterator class.

Jeff Gruenbaum
  • 364
  • 6
  • 21
1

That's because you're exhausting the iterator.

Use this:

xr = list(zip(range(0, 5), range(0, 5)))
yr = list(zip(range(3, 4), range(0, 1)))

print(xr, yr)
print(xr)
Balaji Ambresh
  • 4,977
  • 2
  • 5
  • 17
  • What is meant by "exhausting the generator"? Is there any reference you can point to? – paradocslover Jun 02 '20 at 17:36
  • The [iterator](https://docs.python.org/3/library/functions.html#zip) is exhausted after traversal. Your usage requires more than once usage of the result. So, turn it into a list. – Balaji Ambresh Jun 02 '20 at 17:44
  • This solution works perfectly! I didn't know about how iterators could only be used once, so thanks! – oriont Jun 02 '20 at 17:54