Understanding
Map, Filter, and Reduce



What are Map, Filter, and Reduce?

Map, 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.

Why use Map, Filter, Reduce?

Understanding 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)

Output:

[1, 4, 9, 16, 25]

What's happening here?

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.

Question:

What if you wanted to double every number instead?

Answer: You’d just pass a double function instead of square to map().

Understanding 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)

Output:

[2, 4, 6]

Question:

What does filter() return?

Answer: A new collection that only contains elements that passed the test defined by the function.

Understanding 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)

Output:

10

What’s happening here?

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.

Question:

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.

Combining Map, Filter, and Reduce

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)

Output:

56

This applies filter() to keep evens → [2, 4, 6], then map() to square → [4, 16, 36], then reduce() to sum → 56.

When to Use Map, Filter, Reduce

Conclusion

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.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M