2

The following code:

coords = zip([0], [0])
for a, b in list(coords):
    print("{}, {}".format(a, b))

outputs 0, 0 as expected. But the following code:

coords = zip([0], [0])
mylist = list(coords)
for a, b in list(coords):
    print("{}, {}".format(a, b))

outputs nothing. Why is that the case?

Python version:

Python 3.6.3 |Anaconda, Inc.| (default, Oct 13 2017, 12:02:49) 
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
András Gyömrey
  • 1,770
  • 1
  • 15
  • 36

1 Answers1

4

Because zip returns an iterator, which means that once you iterate over it, it's exhausted and you cannot iterate over it again.

Your first iteration is being done when you make it a list:

mylist = list(coords)
# At this point coords has been exhausted, so any further `__next__` calls will just raise a `StopIteration`

When you try to iterate over it again using the for loop, it doesn't yield any more items, because there's nothing else to return. Everything has been iterated using list.

In order for your for loop to work, you need to either:

  • Loop over mylist, which is a list and hence it keeps indices of the items (it can be randomly accessed), which means that you can go over all the elements as many times as you want.
  • Get a fresh iterator by calling zip([0], [0]) again.
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154