Python: casting map object to list makes map object empty?

A map object is a generator returned from calling the map() built-in function. It is intended to be iterated over (e.g. by passing it to list()) only once, after which it is consumed. Trying to iterate over it a second time will result in an empty sequence.

If you want to save the mapped values to reuse, you’ll need to convert the map object to another sequence type, such as a list, and save the result. So change your:

my_map = map(...)

to

my_map = list(map(...))

After that, your code above should work as you expect.

Leave a Comment