Python iterator is empty after performing some action on it

This is exactly how iterators work. They’re designed to generate data on the fly exactly one time, no more. If you want to get data out of it a second time, you either have to save all the iterated data to another list, or initiate the iterator again. In cases where you need to read from files or do other annoying things to re-obtain that iterator, it’s probably best to just store that data in a list when it’s generated.

>>> numbers = ('1','2','3','4','5')
>>> ints = [x for x in map(int, numbers)]
>>> print(list(ints))
[1, 2, 3, 4, 5]
>>> print(list(ints))
[1, 2, 3, 4, 5]

https://docs.python.org/2/library/stdtypes.html#iterator-types

The intention of the protocol is that once an iterator’s next() method
raises StopIteration, it will continue to do so on subsequent calls.
Implementations that do not obey this property are deemed broken.
(This constraint was added in Python 2.3; in Python 2.2, various
iterators are broken according to this rule.)

I should note that I ran the exact code you gave on Python 2.4.3, and it printed out the list every time. So it’s a version dependent thing, I suppose.

Leave a Comment