Map and list comprehensions

In class, we saw that map(f,L) applies the function f to the list L. For example, if dbl is the function

 

def dbl(x):

""" input: a number x (int or float)

output: twice the input

"""

return 2*x

then we could us it in map as follows:

>>> map( dbl, [1,2,3] )

[2, 4, 6]

If you wrote dbl to return 2.0*x instead of 2*x, your resulting list will contain floats instead of ints.

 

Try it!

Paste the dbl function from above into your hw2pr1.py file (or any other python file) and load it with F5

Then, from your shell window, try some variants of the above call to map and the list comprehension above to ensure that they do what you expect:

 

>>> map( dbl, [20,21,21.21] )

[40, 42, 42.420000...0002]

 

>>> map( dbl, range(0,100) )

(lots of even numbers here...)

 

List comprehensions: Mapping without map

map's ability to apply a function to each element in a list is so valuable and so commonly used that Python offers a special syntax so that you don't even have to use the term map:

 

>>> [ dbl(x) for x in [1,2,3] ]

[2, 4, 6]

 

The idea here is that x represents each element in the list [1,2,3], in turn. The function dbl is then applied to each of these values to create the new list. These are called list comprehensions.

In your Python shell try out the following list comprehensions to get a feel for how they work:

 

>>> [ dbl(x) for x in [21, 22] ]

>>> [ 2*x for x in range(10) ]

 

# The list can be empty...

>>> [ dbl(x) for x in [] ]

# The list itself can come from another function.

>>> [ dbl(x) for x in range(21,23) ]

# We can use any variable name, x, y, or whatever we like

>>> [ dbl(y) for y in range(21,23) ]

# Or no variable name at all! Hooray!

>>> [ dbl(21) for x in range(0,100) ]

An example

As with everything in Python, once you've tested something out in the interpreter (the >>> prompt), you might consider putting it to use in a function. For example, consider writing a function to output the first N nonnegative doubles:

 

def doubles(N):

""" input N: a nonnegative int

output: a list of N even integers, starting from 0

"""

return [ 2*x for x in range(N) ]


We could also have written that last line as

return [ dbl(x) for x in range(N) ]

which would have used the dbl function already in our file. Either way, we can then use this definition of doubles:

 

>>> doubles(22)

[0, 2, 4, 6, 8, 10, 12, 14, 16,

18, 20, 22, 24, 26, 28, 30,

32, 34, 36, 38, 40, 42]

 

Back:

Lab 2, Problem 1