Introduction
Let’s go deeper into the Python sea and discover the beauties of functional programming. Today, we’ll look at three useful built-in functions: map(), filter(), and reduce(). These are crucial to the functional programming paradigm because they allow you to build cleaner, more efficient code.
The Three Key Functions
map() Function
map() applies a function to all items in an input list. Here’s an example:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Outputs: [1, 4, 9, 16, 25]
In this example, we’ve used map() to square every number in the list.
filter() Function
filter() creates a list of elements for which a function returns true. Here’s how you use it:
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x%2 == 0, numbers))
print(even_numbers) # Outputs: [2, 4]
We used filter() to get all the even numbers from the list.
reduce() Function
reduce() applies a rolling computation to sequential pairs of values in a list and returns a single result. Note: You need to import it from the functools module. Here’s an example:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x*y, numbers)
print(product) # Outputs: 120
We used reduce() to calculate the product of all numbers in the list.
Exercise
Your turn! Write a Python program that uses map(), filter(), and reduce() functions to perform the following tasks:
- Takes a list of numbers from 1 to 10
- Uses
map()to square the numbers in the list - Uses
filter()to extract numbers greater than 10 - Uses
reduce()to find the product of the remaining numbers
Conclusion
Congratulations on learning about Python’s functional programming features! Understanding map(), filter(), and reduce() can substantially improve your Python game. Continue to hone these skills as you progress through your Python journey. Pythonistas, have fun coding!
