TUTORIAL

Map Function

This section introduces the Python map function

On this page

The map function is the simplest of the built-in functions for functional programming in Python. map() applies the specified function to each element in an iterable sequence:

names = ["Fred", "Wilma", "Barney"]

Python 3.x3.0

map(len, names)  # map in Python 3.x is a class; its instances are iterable
# Out: <map object at 0x00000198B32E2CF8>

Specifically, it means applying the len() function to each element in the list, but it returns an instance of a map object, and you can use the __next__() function to take out each result one by one.

In Python 2.x, the future_builtins module introduced a map function compatible with Python 3.

Python 2.x2.6

from future_builtins import map  # contains a Python 3.x compatible map()

map(len, names)  # see below
# Out: <itertools.imap instance at 0x3eb0a20>

Or, in Python 2, you can use imap in itertools to get a generator.

Python 2.x2.3

from itertools import imap

map(len, names)  # map() returns a list
# Out: [4, 5, 6]


imap(len, names)  # itertools.imap() returns a generator
# Out: <itertools.imap at 0x405ea20>

The result can be explicitly converted into a list to eliminate the differences between Python 2 and 3:

list(map(len, names))
# Out: [4, 5, 6]

map() can be replaced with an equivalent list comprehension or generator expression:

[len(item) for item in names] # equivalent to Python 2.x map()
# Out: [4, 5, 6]

(len(item) for item in names) # equivalent to Python 3.x map()
# Out: <generator object <genexpr> at 0x00000195888D5FC0>

Concrete Examples of the map Function

You can get the absolute value of each element:

list(map(abs, (1, -1, 2, -2, 3, -3))) # the call to `list` is unnecessary in 2.x
# Out: [1, 1, 2, 2, 3, 3]

map also supports anonymous function operations on lists,

map(lambda x: x * 2, [1, 2, 3, 4, 5])
# Out: [2, 4, 6, 8, 10]

We can also use a custom function, such as converting decimal values to percentages:

def to_percent(num):
    return num * 100


list(map(to_percent, [0.95, 0.75, 1.01, 0.1]))
# Out: [95.0, 75.0, 101.0, 10.0]

Or convert dollars to euros (given the exchange rate):

from functools import partial
from operator import mul

rate = 0.9  # fictitious exchange rate, 1 dollar = 0.9 euros
dollars = {"hidden somewhere": 1000, "jeans": 45, "bank": 5000}

# Below it gives the values in Euro
sum(map(partial(mul, rate), dollars.values()))
# Out: 5440.5

functools.partial is a convenient way to give arguments to a function so that they can be used with map instead of using a lambda or creating a custom function.