Yes, generators must be consumed once. Each time we iterate over the generator, we ask it to give us a different value, and if no more values ββare added to eliminate the StopIteration exception, which would stop the iteration. There is no way for the generator to know that we want to repeat it without cloning it.
While the records can fit comfortably in memory, I would use a list instead:
top_stories = list(top_stories)
This way you can iterate over top_stories multiple times.
There, a function called itertools.tee copies an iterator, which can also help you, but sometimes more slowly than just using a list. Help: http://docs.python.org/library/itertools.html?highlight=itertools.tee#itertools.tee
Baversjo
source share