You are here

Map, filter and reduce

4 September, 2015 - 14:38

To add up all the numbers in a list, you can use a loop like this:

def add_all(t):
    total = 0
    for x in t:
        total += x
    return total

total is initialized to 0. Each time through the loop, x gets one element from the list. The += operator provides a short way to update a variable. This augmented assignment statement:

total += x

is equivalent to:

total = total + x

As the loop executes, total accumulates the sum of the elements; a variable used this way is sometimes called an accumulator.

Adding up the elements of a list is such a common operation that Python provides it as a built-in function, sum:

»»»t= [1, 2, 3J »»» sum(t) 6 

An operation like this that combines a sequence of elements into a single value is sometimes called reduce.

Exercise 10.1.Write a function called nested_sumthat takes a nested list of integers and add up the elements from all of the nested lists.

Sometimes you want to traverse one list while building another. For example, the following function takes a list of strings and returns a new list that contains capitalized strings:

def capitalize_all(t):
    res = []
    for s in t:
        res.append(s.capitalize())
    return res

res is initialized with an empty list; each time through the loop, we append the next element. So res is another kind of accumulator.

An operation like capitalize_all is sometimes called a map because it “maps” a function (in this case the method capitalize) onto each of the elements in a sequence.

Exercise 10.2.Use capitalize_allto write a function named capitalize_nestedthat takes a nested list of strings and returns a new nested list with all strings capitalized.

Another common operation is to select some of the elements from a list and return a sublist. For example, the following function takes a list of strings and returns a list that contains only the uppercase strings:

def only_upper(t):
    res = []
    for s in t:
    if s.isupper():
        res.append(s)
return res

isupper is a string method that returns True if the string contains only upper case letters.

An operation like only_upper is called a lterbecause it selects some of the elements and filters out the others.

Most common list operations can be expressed as a combination of map, filter and reduce. Because these operations are so common, Python provides language features to support them, including the built-in function map and an operator called a “list comprehension.”

Exercise 10.3. Write a function that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the rsti+ 1 elements from the original list. For example, the cumulative sum of [1, 2, 3]is [1, 3, 6].