map filter reduce · Exercises
Core Python

map filter reduce Exercises

4 exercises that build on the Python map, filter and reduce lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: map() transforms every item of an iterable, filter() keeps only the items that pass a test, and functools.reduce() folds all the items into a single value by combining a running result with each item in turn. By the end you can transform, select and combine items with map(), filter() and reduce(), chain them into a pipeline, avoid the lazy and one-use pitfalls, and choose between them and a comprehension. You will practise: Clean up a list of names; Predict the pipeline; Fix the letter counter; Average of the students who showed up.

0 / 4 completed

map filter reduce practice exercises

1. Clean up a list of names

Write code Easy

Write a function clean_names(names) that takes a list of messy names such as " asha " or "BEN" and returns a list where every name has no spaces around it and starts with a capital letter, for example "Asha" and "Ben".

Use map() with the built-in string methods str.strip and str.title. Remember that map() is lazy: return a real list.

Your code
def clean_names(names):
    # use map() with str.strip and str.title, and return a list
    pass

print(clean_names(["  asha ", "BEN", "  mia  "]))

2. Predict the pipeline

Predict the output Easy

Read the code and type exactly what it prints, line by line. Pay attention to which iterators are already used up when a line runs. Then press Check to run it and compare.

Read this code
numbers = [1, 2, 3, 4, 5, 6]
evens = filter(lambda n: n % 2 == 0, numbers)
squares = map(lambda n: n * n, evens)

print(list(squares))
print(list(evens))
print(sum(map(len, ["ab", "cde", ""])))
print(list(filter(None, [0, 3, "", "hi", [], [0]])))

3. Fix the letter counter

Fix the bug Medium

count_letters(words) should add up the number of letters in all the words, so the program should print 13. Instead it crashes. Fix the function. It should also return 0 for an empty list.

Your code
from functools import reduce

def count_letters(words):
    return reduce(lambda total, word: total + len(word), words)

print(count_letters(["pear", "fig", "banana"]))

4. Average of the students who showed up

Write code Hard

Write class_average(students). students is a list of (name, score) pairs, and the score is None for a student who was absent.

Build it as a pipeline: filter the students who were present, map them to their scores and reduce the scores to a total. Return the average of the present students rounded to 1 decimal place, or 0.0 when nobody was present.

Careful: a present student can score 0, and that score still counts.

Your code
from functools import reduce

def class_average(students):
    """students is a list of (name, score) pairs; the score is None for an absent student."""
    # 1. filter: keep the students who were present (score is not None)
    # 2. map: take just the scores
    # 3. reduce: add the scores up
    # Return the average rounded to 1 decimal place, or 0.0 when nobody was present.
    pass

print(class_average([("Asha", 80), ("Ben", None), ("Chen", 60)]))

Next lessonPython any() and all()

More Python map, filter and reduce examples · All Python exercises