Python3 get error when constructing a map object by list constructor

Question:

list_of_input = map(float,[1,2,3])
print(list(list_of_input)[0])
print(list(list_of_input)[0])

IndexError: list index out of range

Why does this error occur?

Asked By: marco73824192

||

Answers:

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.

Answered By: thelogicalkoan

in Python 3 map() returns an iterator not a list. When you pass this iterator to list the first time it consumes the iterator so the second time you get an empty list, hence the IndexError.

Answered By: bruno desthuilliers
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.