Python provides functional programming tools such as map(), filter(), and reduce() to process data efficiently.
- map() – Apply a function to all items in an iterable
- filter() – Filter items based on a condition
- reduce() – Apply a function cumulatively to items (requires
functools)
These functions are commonly used for data transformation, aggregation, and filtering.
Why Map, Filter, and Reduce Are Important
- Enable concise and readable code
- Efficiently handle large datasets
- Useful in data analysis, machine learning, and automation
- Reduce the need for explicit loops
Example 1: Using map()
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
- Transforms data efficiently without loops
Example 2: Using filter()
numbers = [10, 15, 20, 25, 30]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [10, 20, 30]
- Filters data based on conditions for cleaner datasets
Example 3: Using reduce()
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 120
- Combines all elements using a cumulative function
- Real-world use: calculating totals, products, or aggregations
Example 4: Real-World Scenario – Combining All Three
from functools import reduce
# List of numbers
numbers = [1, 2, 3, 4, 5, 6]
# Filter even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Square them
squared_evens = list(map(lambda x: x**2, evens))
# Sum the squares
total = reduce(lambda x, y: x + y, squared_evens)
print(f"Sum of squares of even numbers: {total}")
# Output: 56
- Shows combined real-world usage of map, filter, and reduce
Best Practices
✔ Use map and filter with lambda for small, readable operations
✔ Use reduce from functools only for cumulative operations
✔ Prefer list comprehensions if readability is better
✔ Always handle large datasets efficiently
Conclusion
Python’s map, filter, and reduce functions provide concise and efficient ways to transform, filter, and aggregate data. Mastering these functions is essential for data-driven applications, analytics, and real-world programming tasks.
References
- Internal Reference: https://savanka.com/category/learn/python/
- External Reference: https://www.w3schools.com/python/