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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0