1

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?

  • Could not repro the error, its working on my end – shahidammer Sep 08 '18 at 07:22
  • because when you generate use the function [map](https://docs.python.org/3/library/functions.html#map) this return a iterator, once this is converted to a list the [iterator](https://anandology.com/python-practice-book/iterators.html#the-iteration-protocol) pull all the values, , so the next time the list_of_input is converted to a list value will be a [] – Leonardo Orozco Sep 08 '18 at 07:32

2 Answers2

0

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.

thelogicalkoan
  • 620
  • 1
  • 5
  • 13
0

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.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118