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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With