Python: Calling 'List' on a Map Object Twice

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

When I convert a map object to list object in Python using list(), and apply list() again to this list, why does the list become empty?

The map object is a generator.

list(result)

involves iterating through the iterator. The iterator is now finished. When you try again, there is no data to return, so you have an empty list. If you reset the iterator in some way, you can get the expected results.

This is something like reading an entire file, and then wondering why your next read loop doesn't return anything: you're at the end.

Python3 get error when constructing a map object by list constructor

The conversion of a map to list is done only once, meaning map is a generator object and once you transform it to list, it gets exhausted : python 3: generator for map. So the error comes from second print statement and not the first.

Unexpected behavior in Python 3: The list contents disappear after printed

newList is not a list. It's a generator that yields data on demand and will be exhausted after you retrieve all the data it holds with list(newList). So, when you call list(newList) again, there's no more data to put in the list, so it remains empty.



Related Topics



Leave a reply



Submit