Codele / Advanced programming
Map, filter and reduce
Three reusable moves work on a whole list: change every item, keep only some, or boil the list down to one value. Picture a conveyor belt with three stations.
- map makes a new list the same length: the small function is run on every item. map(x → x times 2) turns 1, 2, 3 into 2, 4, 6.
- filter keeps only the items for which a yes or no question says yes. The new list can be shorter, or even empty.
- reduce (some languages say fold) combines the items one by one into a single value, such as a total. It needs a starting value.
- None of the three changes the original list: each hands back something new. Python usually writes map and filter as list comprehensions. Java and C# have them in streams and LINQ, and C++ has algorithms such as transform. In Python 3, map and filter hand items out lazily, so list() collects them.
- Go has no built-in versions, so we wrote small generic helpers. Writing a plain loop is normal in Go.
Loading the playable lesson…