⬅ Previous Topic
First-Class Functions in ProgrammingNext Topic ⮕
Lambda Functions⬅ Previous Topic
First-Class Functions in ProgrammingNext Topic ⮕
Lambda FunctionsMap, Filter, and Reduce are foundational concepts in functional programming. They are used to process data collections in a declarative way, often replacing the need for explicit loops.
map()
The map function applies a given transformation to each item in a collection and returns a new collection with the transformed results.
function square(x):
return x * x
numbers = [1, 2, 3, 4, 5]
squared = map(square, numbers)
print(squared)
[1, 4, 9, 16, 25]
The square
function is applied to every element of the numbers
list. The original list remains unchanged, and a new list is returned with squared values.
What if you wanted to double every number instead?
Answer: You’d just pass a double
function instead of square
to map()
.
filter()
The filter function selects elements from a collection that satisfy a given condition (i.e., for which a function returns true
).
function isEven(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
evens = filter(isEven, numbers)
print(evens)
[2, 4, 6]
What does filter()
return?
Answer: A new collection that only contains elements that passed the test defined by the function.
reduce()
The reduce function applies a binary function cumulatively to the items of a collection, reducing the collection to a single value.
function add(x, y):
return x + y
numbers = [1, 2, 3, 4]
sum = reduce(add, numbers)
print(sum)
10
The add
function is called like this: add(1, 2) → 3
, then add(3, 3) → 6
, then add(6, 4) → 10
. The result is a single value: 10
.
Can reduce()
be used to find the maximum value?
Answer: Yes! Just use a function like max(a, b): return a if a > b else b
.
You can often combine these for powerful one-liners. Let’s say we want to sum the squares of even numbers from a list.
function isEven(x): return x % 2 == 0
function square(x): return x * x
function add(a, b): return a + b
numbers = [1, 2, 3, 4, 5, 6]
result = reduce(add, map(square, filter(isEven, numbers)))
print(result)
56
This applies filter()
to keep evens → [2, 4, 6], then map()
to square → [4, 16, 36], then reduce()
to sum → 56.
These three functions make your code cleaner, expressive, and less error-prone. By practicing them with basic use-cases, you can greatly improve your understanding of functional programming principles.
⬅ Previous Topic
First-Class Functions in ProgrammingNext Topic ⮕
Lambda FunctionsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.