From CS 61A Wiki
Revision as of 20:12, 23 June 2014 by Axis (Talk | contribs)

Jump to: navigation, search

map is a built-in, higher-order, list-comprehensive function available in the Python interpreter.

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.

The Python 2.7 map built-in will always return a list, regardless of the type of iterable passed. The Python 3.2+ map built-in will return a map-object which can easily be converted into a list.


General Form

In Python, the most general form of the map function is as follows:

map(fn, itr)

where the function being applied is fn and the lone iterable is itr.

Alternate Forms

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.

map(None, itr)

When the given function is None, map assumes the identity function. If more than one iterable is offered and the given function is None, 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]

Mapping add_one to 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, 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. Applying 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


Using None as a function