Chapter 6: Higher order functions

The map function

face Josiah Wang

Examine the following code. What does it do?

>>> numbers = [str(item) for item in [1, 3, 5, 7, 9]]
>>> print(numbers)
['1', '3', '5', '7', '9']
>>> print(",".join(numbers))
1,3,5,7,9

You are correct if you said it converts each number in the list to a string, and then joins up the strings.

The map function

You can also achieve the same thing with a built-in higher-order function called map().

The function map(func, iterable) applies a function func to each element in iterable, and returns a map object (which is an iterable).

In the example below, 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>
>>> number_list = list(numbers) 
>>> print(number_list)
['1', '3', '5', '7', '9']
>>> print(",".join(number_list))
1,3,5,7,9

Exercise

Use map() to return a new list containing the length of each item in the original list. Feel free to also implement a list comprehension version if you wish to practise that!

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

lengths = ????

assert lengths == [5, 6, 9, 4]

A possible solution with map():

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

lengths = list(map(len, fruits))

assert lengths == [5, 6, 9, 4]

A possible solution with list comprehension:

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

lengths = [len(fruit) for fruit in fruits]

assert lengths == [5, 6, 9, 4]

I personally find the list comprehension version a bit more self-explanatory.