Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: calling 'list' on a map object twice

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?

like image 756
ADB Avatar asked Apr 07 '16 20:04

ADB


1 Answers

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
like image 145
Łukasz Rogalski Avatar answered Oct 17 '22 23:10

Łukasz Rogalski