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.
asked Feb 11, 2019 at 12:45
2
  • 4
    You have exhausted the generator here mylist = list(coords) Commented Feb 11, 2019 at 12:48
  • Thank you for your comment. Just found out what I need to do in such a case: stackoverflow.com/questions/1271320/… Commented Feb 11, 2019 at 12:51

1 Answer 1

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.
answered Feb 11, 2019 at 12:51
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.