Python difference between filter() and map()

In map: Function will be applied to all objects of iterable. In filter: Function will be applied to only those objects of iterable who goes True on the condition specified in expression.


They both work a little bit differently but you've got the right idea.

Map takes all objects in a list and allows you to apply a function to it Filter takes all objects in a list and runs that through a function to create a new list with all objects that return True in that function.

Here's an example

def square(num):
    return num * num

nums = [1, 2, 3, 4, 5]
mapped = map(square, nums)

print(*nums)
print(*mapped)

The output of this is

1 2 3 4 5
1 4 9 16 25

Here's an example of filter

def is_even(num):
    return num % 2 == 0


nums = [2, 4, 6, 7, 8]
filtered = filter(is_even, nums)

print(*nums)
print(*filtered)

The output of this would be

2 4 6 7 8
2 4 6 8

Tags:

Python