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
András Gyömrey
1,8071 gold badge18 silver badges37 bronze badges
1 Answer 1
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 alistand 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
Matias Cicero
26.5k21 gold badges91 silver badges160 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
mylist = list(coords)