Why map is not executing a function in python 3

Question:

I have written a below small python program

def abc(x):
    print(x)

and then called
map(abc, [1,2,3])

but the above map function has just displayed

<map object at 0x0000000001F0BC88>

instead of printing x value.

I know map is an iterator in python 3, but still it should have printed the ‘x’ value right. Does it mean that abc(x) method is not called when we use “map”?

Asked By: user2225190

||

Answers:

lazy-evaluation

map(or range, etc.) in Python3 is lazy-evaluation: it will evaluate when you need it.

If you want a result of map, you can use:

list(map(abc, [1,2,3]))
Answered By: Robert Lu

The map iterator lazily computes the values, so you will not see the output until you iterate through them. Here’s an explicit way you could make the values print out:

def abc(x):
    print(x)
it = map(abc, [1,2,3])
next(it)
next(it)
next(it)

The next function calls it.__next__ to step to the next value. This is what is used under the hood when you use for i in it: # do something or when you construct a list from an iterator, list(it), so doing either of these things would also print out of the values.

So, why laziness? It comes in handy when working with very large or infinite sequences. Imagine if instead of passing [1,2,3] to map, you passed itertools.count() to it. The laziness allows you to still iterate over the resulting map without trying to generate all (and there are infinitely many) values up front.

Answered By: Trevor Merrifield
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.