Given a function and an iterable (often in the form of a list),
Map works by (1) applying the function to each element of the iterable and (2) returning the result.
In Python, the most general form of the
map function is as follows:
where the function being applied is
fn and the lone iterable is
In addition to the most general form,
map can take many different shapes. The following are a few examples of these alternate forms and the assumptions they carry.
map(fn, itr1, itr2, ...)
When multiple iterables are offered,
fn must take that many arguments. It will then apply the function to each of the iterables in parallel.
When the given function is
map assumes the identity function.
If more than one iterable is offered and the given function is
map will 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
map's resultant list.)
Single argument functions
For the first example, we will use the function
add_one and the basic 5-element list
my_list which we will define as follows:
def add_one(x): return x+1 my_list = [1, 2, 3, 4, 5]
my_list in Python 2.7 would look something like this:
>>>map(add_one, my_list) [2, 3, 4, 5, 6]
If we wanted to do the same in Python 3.2 or later, we would simply convert the result from a map object to a list, and it would look something like this:
>>>list(map(add_one, my_list) [2, 3, 4, 5, 6]
Let's use another function,
multiply_by_two (which we could have named
double!), and a new list,
def multiply_by_two(x): return x*2 new_list = [1, 3, 5, 7, 9]
Just as in the
add_one example, we have to adjust our code depending on the version of Python we want to use.
map in Python 2.7 and using our
multiply_by_two function and
new_list gives us the following:
>>>map(multiply_by_two, new_list) [2, 6, 10, 14, 18]
As before, a change to Python 3.3 simply involves converting the map object to a more user-friendly list.
>>>list(map(multiply_by_two, new_list)) [2, 6, 10, 14, 18]
Multiple argument functions
Now we'll try a few examples where
map takes in a multiple argument function.
In this example, we'll take a basic function,
add_two_things, which does exactly as its namesake suggests. We'll also create the two lists:
your_list, as defined below.
def add_two_things(x, y): return x+y my_list = [1, 2, 3] your_list = [4, 5, 6]
map function with these arguments will combine components from matching indexes of the two lists, as so:
(in Python 2.7)
>>>map(add_two_things, my_list, your_list) [5, 7, 9]
(or in Python 3.2)
>>>list(map(add_two_things, my_list, your_list)) [5, 7, 9]