This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

map()

The first built-in higher-order function that we will look at is map(). This is one that I personally use a lot!

map(func, iterable) applies a function func to each element in iterable, and returns a new list.

For example, we might want to convert a list of numbers to a list of strings. So map() will apply the str() function to each number in the list.

numbers = map(str, [1, 3, 5, 7, 9])
print(numbers)       ## <map object at 0x7f50d50d41c0>

# map() returns an iterable. So you will need to cast it to a list
number_list = list(numbers)  
print(number_list)   ## ['1', '3', '5', '7', '9']

# Use case: join the (string representation) of numbers with commas
print(",".join(number_list))   ## '1,3,5,7,9'

Without map(), you might have to use list comprehension to write something like this:

numbers = [str(item) for item in [1, 3, 5, 7, 9]]

Using lambda functions in map()

So, how do we use lambda functions here?

For example, we might want to apply some mathematical operation to every number in a list numbers.

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

A list comprehension version of the above code would look like this:

transformed = [3*x+5 for x in numbers]

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) in the traditional way. So in some cases, lambda functions will make the code more readable as the expression is in one place.

Exercises

Task 1

Use map() to return a new list containing the length of each item in the original list.

fruits = ["apple", "banana", "pineapple", "pear"]

## Expected output
## [5, 6, 9, 4]

Task 2

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

The formula is \(F = C * \frac{9}{5} + 32\), where \(F\) is the temperature in Fahrenheit, and \(C\) the temperature in Celcius.

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

## Expected output
## [44.6, 122.0, 53.6, 71.6, 86.0]