Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python iterator is empty after performing some action on it

I was trying to do a challenge on codeeval in python3 and got stuck trying to improve my solution. Every time i tried to iterate (or print, or some other action) two times consecutively over the same iterator, the second loop came up empty. Here is a minimal example that produces this behavior, although I tried several different combinations with lists etc. that gave me the same result:

numbers = ('1','2','3','4','5')
numbers = map(int, numbers)                                                    
print(list(numbers))                                                          
print(list(numbers))

results in:

[1, 2, 3, 4, 5]
[]

Why does print (in this case) delete the content of numbers?

like image 451
Guerki Avatar asked Jul 30 '14 14:07

Guerki


1 Answers

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.

like image 114
TheSoundDefense Avatar answered Oct 13 '22 00:10

TheSoundDefense