Codementor Events

Difference between Map and Filter functions in Python

Published May 22, 2020Last updated Dec 22, 2021
Difference between Map and Filter functions in Python

In Python, map and filter functions look similar and establishing the difference between the two might be sometime confusing.

In this post, I would like to highlight the basic difference between the two functions with clear examples.

While Maps takes a normal function, Filter takes Boolean functions. As a matter of fact, filter are maps with conditional logic, a Boolean logic.

Let's put this into perspective with examples.

nums = [11, 22, 33, 44, 55]

Below is an example using map

map = list(map(lambda x: x**2, nums))
print(map)

[121, 484, 1936, 3025]
Below is an example using filter

filter = list(filter(lambda x: x%2==0, nums))
print(filter)

[22, 44]
As you can see, the two examples modified the nums list. But while Map modifies the list with a normal logic that produces another list, Filter modifies the list with conditional logic that filters out some elements--those that do not meet the conditions of the Boolean logic---from the nums list.

I hope this brings a clearer picture into the concept of map and filter in python.

Thanks

Discover and read more posts from Babatunde
get started