Simple map function error

1.4k Views Asked by At

I am trying out the map function and it is giving me unexpected output:

map(lambda x: x, range(3))
<builtins.map at 0x7fc3f6c0ab70>

When I try to call it with map(lambda x: x, range(3))(), it says map is not callable.

2

There are 2 best solutions below

0
On

I think what you're looking for is

>>> list(map(lambda x: x, range(3)))
[0, 1, 2]

map returns an iterator. The message you are seeing is simply the object type for which you have just created an instance

>>> map(lambda x: x, range(3))
<map object at 0x02E11F10>
3
On

That is not an error.

Instead, it is a representation of the map object (an iterator) returned by map in Python 3.x:

>>> # Python 3.x interpreter
>>> map(lambda x: x, range(3))
<map object at 0x01AAA2F0>
>>> type(map(lambda x: x, range(3)))
<class 'map'>
>>>

Note that my output is not exactly the same because I am using a different implementation. Still, the same principle applies.

map in Python 2.x meanwhile returns a list:

>>> # Python 2.x intepreter
>>> map(lambda x: x, range(3))
[0, 1, 2]
>>>

But in modern Python, if you want a list result, you need to explicitly convert the map object into one:

>>> # Python 3.x interpreter
>>> list(map(lambda x: x, range(3)))
[0, 1, 2]
>>>

You can read about this as well as similar changes on Python's What's New in Python 3.0 page.