The map function is the simplest one among Python built-ins used for functional programming. map()
applies a specified function to each element in an iterable:
names = ['Fred', 'Wilma', 'Barney']
map(len, names) # map in Python 3.x is a class; its instances are iterable
# Out: <map object at 0x00000198B32E2CF8>
A Python 3-compatible map
is included in the future_builtins
module:
from future_builtins import map # contains a Python 3.x compatible map()
map(len, names) # see below
# Out: <itertools.imap instance at 0x3eb0a20>
Alternatively, in Python 2 one can use imap
from itertools
to get a generator
map(len, names) # map() returns a list
# Out: [4, 5, 6]
from itertools import imap
imap(len, names) # itertools.imap() returns a generator
# Out: <itertools.imap at 0x405ea20>
The result can be explicitly converted to a list
to remove the differences between Python 2 and 3:
list(map(len, names))
# Out: [4, 5, 6]
map()
can be replaced by 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>