Chapter 6: Higher order functions

map with lambda functions

face Josiah Wang

We now want to apply some mathematical operation to every number in the list of numbers.

Using list comprehension, we might do it this way.

>>> numbers = [1, 3, 5, 7, 9]
>>> transformed = [3*x+5 for x in numbers]
>>> print(transformed)
[8, 14, 20, 26, 32]

The map solution

Using map(), it gets a bit messy because we might have to define the function first.

>>> def transform(x):
...    return 3*x + 5
...
>>> numbers = [1, 3, 5, 7, 9]
>>> transformed = list(map(transform, numbers))
>>> print(transformed)
[8, 14, 20, 26, 32]

But - we don’t have to name the function, do we? Remember lambda functions? Can we use them here to save us from having to explicitly define the transform() function?

>>> numbers = [1, 3, 5, 7, 9]
>>> transformed = list(map(lambda x: 3*x+5, numbers))
>>> print(transformed)
[8, 14, 20, 26, 32]

Another example: perhaps we want to Capitalize each word in the list, and also repeat them?

>>> greetings = ["hello", "bonjour", "hola", "ciao"]
>>> transformed = list(map(lambda x: x.capitalize()*2, greetings))
>>> print(transformed)
['HelloHello', 'BonjourBonjour', 'HolaHola', 'CiaoCiao']

This is the same as the following using list comprehension.

transformed = [greeting.capitalize()*2 for greeting in greetings]

Lambda functions are useful in these examples as they are simple expressions. Without lambda functions, you will have to explicitly define a function (e.g. capitalize_and_repeat). So in some cases, lambda functions will make the code more readable as the expression is in a single place.

Exercise

Use map() and lambda functions to convert a list of temperatures (in Celsius) to Fahrenheit.

The formula is F=C\times\frac{9}{5}+32, where F is the temperature in Fahrenheit, and C the temperature in Celsius.

As usual, feel free to also implement a list comprehension version as a comparison.

c_temperatures = [7, 50, 12, 22, 30]

f_temperatures = ????

assert f_temperatures == [44.6, 122.0, 53.6, 71.6, 86.0]

A possible solution with map() and lambda functions:

c_temperatures = [7, 50, 12, 22, 30]

f_temperatures = list(map(lambda c: c*9/5+32, c_temperatures))

assert f_temperatures == [44.6, 122.0, 53.6, 71.6, 86.0]

A possible solution with list comprehension:

c_temperatures = [7, 50, 12, 22, 30]

f_temperatures = [temp*9/5 + 32 for temp in c_temperatures]

assert f_temperatures == [44.6, 122.0, 53.6, 71.6, 86.0]