Lesson 16 of 55
11 mins readPython Higher-Order Functions: map, filter, foldl & foldr
In Plain English
Higher-order functions take or return other functions. Master map (transformation), filter (selection), foldl (tail-recursive left reduction), and foldr (lazy right reduction).
Deep Dive: How It Works
map: map f xs applies f to each item in xs.
filter: filter p xs keeps elements satisfying predicate p.
foldl vs foldr: foldl reduces from left to right (accumulator first); foldr reduces from right to left and can work on infinite lists when lazy.
sum and product: sum = foldl (+) 0 and product = foldl (*) 1.
Core Rules to Remember

foldl & foldr: Universal reduction primitives that generalize all list processing algorithms.

Lazy foldr: foldr can short-circuit and terminate even on infinite lists.
Live Interactive Example
Hit Run Code to see it liveFolds, Map, and Filter Pipeline
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
Output Console
Click "Run Code" to view the rendered output.
How it works: filter even gives [2, 4, 6] -> map (^2) gives [4, 16, 36] -> foldl (+) gives 56.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Compute Product with foldl
Compute `foldl (*) 1 [1, 2, 3, 4, 5]` and print `"Product: "` followed by its `show` string.
1
2
3
4
5
6
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.