- In Python 2,
mapreturns a list, regardless of the type of iterable passed.
- In Python 3,
mapreturns an iterable map object, which can be converted into a sequence using the appropriate constructor (e.g.,
- 1 Forms
- 2 Examples
- 3 Sources
The most general form of the
map function is:
where the function being applied is
fn and the lone iterable is
fn must be a one-argument function.
map has alternate forms:
When multiple iterables are offered,
map(fn, itr1, itr2, ...)
fnmust take that many arguments. It will then apply the function to each of the iterables in parallel.
In Python 2, when the given function is
mapassumes the identity function (
lambda x: x). This only works for Python 2 — attempting this in Python 3 will result in a
'NoneType' object is not callableerror.
- If more than one iterable is provided,
mapwill create tuples using elements from each iterable in the final list (e.g, the first element of the first iterable and the first element of the second iterable will be combined in a tuple to form the first element of the returned list).
def increment(x): return x + 1 lst = [1, 2, 3, 4, 5] # Python 2 >>> map(increment, lst) [2, 3, 4, 5, 6] # Python 3 >>> list(map(increment, lst) [2, 3, 4, 5, 6]
def double(x): return x * 2 lst = [1, 3, 5, 7, 9] # Python 2 >>> map(double, lst) [2, 6, 10, 14, 18] # Python 3 >>> list(map(double, lst)) [2, 6, 10, 14, 18]
Now we'll try a few examples where
map takes in a multiple-argument function and multiple iterables.
In this example, we use a function,
add_two_things, which does exactly as its name suggests. We also create two lists:
def add_two_things(x, y): return x + y lst1 = [1, 2, 3] lst2 = [4, 5, 6]
map function with these arguments will combine items from matching indices of the two lists:
# Python 2 >>> map(add_two_things, lst1, lst2) [5, 7, 9] # Python 3 >>> list(map(add_two_things, lst1, lst2)) [5, 7, 9]
Suppose we wanted to multiply the elements of two lists by each other.
map would be an incredibly convenient way to do so! We'll define our lists,
lst2, and our multiplication function,
def multiply_by_each_other(x, y): return x * y lst1 = [2, 4, 6] lst2 = [5, 8, 10]
# Python 2 >>> map(multiply_by_each_other, lst1, lst2) [10, 32, 60] # Python 3 >>> list(map(multiply_by_each_other, list_a, list_b)) [10, 32, 60]
None as the function (only for Python 2)
None as the function is analogous to using the
A single iterable
In the case of a single list,
map will simply return the identity of the list. We define
lst and then pass it into
>>> lst = [7, 12, 33] >>> map(None, lst) [7, 12, 33]
Multiple iterables can passed as arguments along with
None into the
map function. We create three lists:
lst1 = [1, 2, 3, 4] lst2 = [5, 7, 9, 11] lst3 = [12, 14, 16, 18]
>>> map(None, lst1, lst2, lst3) [(1, 5, 12), (2, 7, 14), (3, 9, 16), (4, 11, 18)]
The first element from each list is combined into a tuple in the resulting list. The second tuple is a combination of the second elements, and so on.