Skip to content Skip to sidebar Skip to footer

Is The Python Map Function A Value-returning Function?

I've been trying to work with the map function in Python, and I've been having a little bit of trouble with it. I can't tell which of these is the proper way to map function foo to

Solution 1:

In Python 2, map() returns a list of return values of foo(...). If you don't care about the results and just want to run the elements of bar through foo, either of your examples will work.

In Python 3, map() returns an iterator that is evaluated lazily. Neither of your examples will actually run any elements of bar through fooyet. You will need to iterate over that iterator. The simplest way would be to convert it to a list:

list(map(foo, bar))

Solution 2:

map returns a new list, and does not change the one you enter into the function. So, the usage is:

deffoo(x): #sample functionreturn x * 2

bar = [1, 2, 3, 4, 5]
newBar = map(foo, bar)

In the interpreter:

>>>print bar
[1, 2, 3, 4, 5]
>>>print newBar
[2, 4, 6, 8, 10]

Note: This is python 2.x

Solution 3:

In Python 2 map() returns a new list. In Python 3 it returns an iterator. You can convert it into a list with:

new_list = list(map(foo, bar))

As the name suggests, a common use of an iterator is to iterate over it:

for x inmap(foo, bar):
    # do something with x

This produces one value at a time without putting all values in memory as creating a list would.

Furthermore, you can do single steps through an iterator:

my_iter = map(foo, bar)
first_value = next(my_iter)
second_value = next(my_iter)

Now work with the rest:

forx in map(foo, bar):
    # x starts from the third value

This is very common in Python 3. zip and enumerate also return iterators. Often this is called lazy evaluation, because values are only produce when really need.

Post a Comment for "Is The Python Map Function A Value-returning Function?"