Python isn’t just about loops and conditionals—it also supports functional programming, which allows you to write cleaner and more expressive code. Two powerful tools in this paradigm are the map() and filter() functions.
In this post, we’ll explore how these functions work, when to use them, and how they can simplify your code.
The map() function applies a given function to each item in an iterable (like a list or tuple) and returns a new iterable (a map object).
map(function, iterable)
numbers = [1, 2, 3, 4]
squared = map(lambda x: x**2, numbers)
print(list(squared)) # [1, 4, 9, 16]
Here, lambda x: x**2 is applied to every element in numbers.
The filter() function filters elements from an iterable based on a condition defined by a function. It returns only the elements for which the function returns True.
filter(function, iterable)
numbers = [1, 2, 3, 4, 5]
even = filter(lambda x: x % 2 == 0, numbers)
print(list(even)) # [2, 4]
Only the elements that satisfy the condition (x % 2 == 0) are included.
Use map() when:
You want to transform each element in a collection.
You’re applying the same operation to every item.
Use filter() when:
You want to select elements based on a condition.
You’re removing unwanted items from a collection.
You can chain them together for powerful data transformations:
numbers = [1, 2, 3, 4, 5]
squared_evens = map(lambda x: x**2, filter(lambda x: x % 2 == 0, numbers))
print(list(squared_evens)) # [4, 16]
First, filter() selects even numbers, then map() squares them.
You don’t always need lambdas. Named functions work too:
def is_even(x):
return x % 2 == 0
def square(x):
return x**2
numbers = [1, 2, 3, 4]
result = map(square, filter(is_even, numbers))
print(list(result)) # [4, 16]
This improves readability, especially in larger projects.
map() and filter() are elegant tools that help you write concise and readable code. They’re especially useful in data processing, machine learning pipelines, and anywhere you need to transform or clean data.
Next time you find yourself writing a loop to modify or filter a list—try using map() or filter() instead!
Next up: Tuples and Immutability