I wanted to calculate the sum of squares up to n. Say n is 4. Then this code generates a list a map object in the range 0 to 4:
m = map(lambda x: x**2, range(0,4))
Ease enough. Now call list on m, and then sum:
>>> sum(list(m)) 14
The unexpected behavior is that if I run the last line again, the sum is 0:
>>> sum(list(m)) 0
I suspect that this is because calling list(m) returns an empty list, but I can’t find an explanation for this behavior. Can someone help me out with this?
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
map returns a stateful iterator in Python 3. Stateful iterators may be only consumed once, after that it’s exhausted and yields no values.
In your code snippet you consume iterator multiple times. list(m) each time tries to recreate list, and for second and next runs created list will always be empty (since source iterator was consumed in first list(m) operation).
Simply convert iterator to list once, and operate on said list afterwards.
m = map(lambda x: x**2, range(0,4)) l = list(m) assert sum(l) == 14 assert sum(l) == 14
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