How to use filter, map, and reduce in Python 3?
Python provides three powerful functions—filter()
, map()
, and reduce()
—for applying functional programming concepts. Below, you’ll see how each one works in Python 3, including code examples and tips for best practices.
1. filter()
- Purpose:
filter()
creates an iterator of elements from an iterable (list, tuple, etc.) for which a certain condition (a function) isTrue
. - Syntax:
filter(function, iterable)
nums = [1, 2, 3, 4, 5, 6] # Filter even numbers is_even = lambda x: (x % 2) == 0 filtered_result = filter(is_even, nums) # In Python 3, 'filter()' returns a filter object (an iterator). # Convert to list if you need a list: filtered_list = list(filtered_result) print(filtered_list) # Output: [2, 4, 6]
- Function: You can use a named function or a lambda function to define the filtering condition.
- Iterator: Remember that in Python 3,
filter()
yields an iterator. To see all the results at once, wrap it inlist()
.
2. map()
- Purpose:
map()
applies a given function to each item of an iterable, returning an iterator of the results. - Syntax:
map(function, iterable[, ...])
(You can pass multiple iterables if your function can handle multiple arguments.)
nums = [1, 2, 3, 4, 5] # Square each number square = lambda x: x * x mapped_result = map(square, nums) mapped_list = list(mapped_result) print(mapped_list) # Output: [1, 4, 9, 16, 25]
- Multiple Iterables: If you provide multiple iterables,
map()
will iterate in parallel, passing one item from each iterable to the function on each loop iteration.
3. reduce()
- Purpose:
reduce()
applies a function of two arguments cumulatively to the elements of a sequence. It effectively reduces the sequence to a single value. - Location: In Python 3,
reduce()
is not a built-in. You must import it fromfunctools
. - Syntax:
reduce(function, iterable[, initializer])
from functools import reduce nums = [1, 2, 3, 4, 5] # Sum of all numbers summation = reduce(lambda x, y: x + y, nums) print(summation) # Output: 15
- Function: The function used by
reduce()
should accept two arguments and return a single value (e.g., summing, multiplying, or combining). - Initializer (Optional): If you specify an
initializer
, it’s placed before the items of the iterable in the computation.
4. When to Use These Functions
filter()
: Best when you need to discard some elements based on a condition, and you still want an iterator or list of the valid elements.map()
: Perfect for transforming each element of an iterable, e.g., squaring numbers, converting strings to integers, etc.reduce()
: Ideal for aggregations (sums, products, merges), but be cautious—sometimes a simple loop or built-in functions (likesum()
) can be more readable and efficient.
5. Combining with List Comprehensions
Many Python developers prefer list comprehensions (or generator expressions) for readability. For instance:
nums = [1, 2, 3, 4, 5] squares = [x * x for x in nums] # Instead of map(...) evens = [x for x in nums if x % 2 == 0] # Instead of filter(...)
While comprehensions are popular for clarity, map()
, filter()
, and reduce()
remain excellent tools, especially when you want to emphasize functional style or handle more complex function-based logic.
Level Up Your Python Skills
If you’re looking to deepen your understanding of Python—especially functional programming patterns, data manipulation, and best practices—these courses from DesignGurus.io can help:
-
Grokking Python Fundamentals
Perfect for anyone aiming to master Python 3, from language basics and built-in functions to practical real-world coding techniques. -
Grokking the Coding Interview: Patterns for Coding Questions
Focused on helping you see the recurring patterns behind coding challenges. Ideal for software engineers prepping for interviews at top tech companies. -
Grokking System Design Fundamentals
If you want to build or design large-scale systems and ace system design interviews, this course is a thorough introduction to distributed systems, scalability, and reliability.
Final Thoughts
filter()
: Use when you want to keep only certain elements based on a condition.map()
: Use when you want to transform each element in an iterable.reduce()
: Use when you want to combine all elements into a single value (and don’t forgetfrom functools import reduce
).
These functions return iterators in Python 3, so convert to a list if you need to access the data all at once. By combining these powerful tools with best coding practices and further learning, you’ll write concise, efficient, and maintainable Python code.
Happy coding!