0

I find that sometimes, if I want to use the result of Python map, I have to surround the call with list. For example:

>>> sum(map( lambda x: x + 1, range(5)))
15
>>> max(map( lambda x: x + 1, range(5)))
5
>>> map( lambda x: x + 1, range(5))[2:3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'map' object is not subscriptable

What I'm looking for is some rule that defines when the addition of list is necessary.

Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
Mark Lavin
  • 1,002
  • 1
  • 15
  • 30
  • I understand iterators and I understand map objects. What I'm *trying* to understand is, why does "sum" and "list" apply to a map object, while "index" does not. – Mark Lavin Aug 07 '23 at 21:21

1 Answers1

0
>>> help(map)
Help on class map in module builtins:

class map(object)
 |  map(func, *iterables) --> map object
 |
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.

here in map( lambda x: x + 1, range(5))[2:3] ,

map( lambda x: x + 1, range(5)) will create an iteratable object, on which you can iteratre (with loop or iter func). you cannot do list slicing on this part [2:3].

to do list slicing, you need to first iterate over this iterable and then save it into list/tuple and then do slicing.

so since you are, directly using list slicing on this, you are facing this error TypeError: 'map' object is not subscriptable

so solution will be first store data in list/tuple by iterating over the map object and then doing slicing

# using list
list(map( lambda x: x + 1, range(5)))[2:3]

# using tuple
tuple(map( lambda x: x + 1, range(5)))[2:3]
sahasrara62
  • 10,069
  • 3
  • 29
  • 44