Map & Filter

In this article, we will see about python map and filter inbuilt methods. In every functional programming you will come across these and is very important to know their usages.

Map

Map applies a function on every element in the iterable and yields the results.

Syntax of map is as follows

map(func, iterable...)

Let’s check out a small example. We will get the nth root of every element in the given list of elements.

def raise_to(p):
    def inner(x):
        return pow(x, p)
    return inner

cube = raise_to(3)

print(list(map(cube, [2, 3, 4, 5])))

OUTPUT
[8, 27, 64, 125]

In the above program we applied function cube to every element using map in the iterable. The output returns raises every element to the power of 3. The function applies on the iterable till it is exhausted.

Filter

Filter is used to remove elements from the iterable for which the function returns False.

Syntax of filter is as follows

filter(func, iterable)

Let us see one common example for filter where I want to filter only even numbers from the given list.

def is_even(x):
    return x if x % 2 == 0 else 0

list(filter(is_even, range(10)))

OUTPUT
[2, 4, 6, 8]

Leave a Reply