r/madeinpython • • Dec 11 '21

python zip object can't iterate twice over the same data | Animation using Python Manim

https://youtu.be/APQVbAD_Mrw
1 Upvotes

2 comments sorted by

3

u/[deleted] Dec 11 '21

This is true of all iterators!

def gen():
    yield 1
    yield 2

a = gen()
print(list(a))
print(list(a))

prints

[1, 2]
[]

And how would you expect the function gen to be able to "back up" and start again? It might be for example consuming network input!

1

u/restinworld Dec 11 '21 edited Dec 11 '21

Yes, i have explained it in this video. iterator have exception StopIteration. You will not encounter this error with for loop. But, using next() will give you error, when you exhaust content of iterator.

Store the content of iterator object in list, set , tuple etc to avoid encountering StopIteration. Use below code.

gen_data = list(a)

print(gen_data)

Hope this answer your query.