Python: calling ‘list’ on a map object twice

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

Leave a Comment