How to use Filters and Maps in Python

In this article, I'm going to be discussing about map() and filter(). Both are built-in functions, you need to import anything.

Summary

Why should you care?

First all, I need to explain to you why would ever want to use a map or filter. Sometimes you want to do some operations in list or even set that requires a loop, however it might be very simple and you just don't want to write 3+ lines of code. Filters and Maps help you to write fewer lines of code and still provide a readable code. With the code, I'll try to convice you that filter() and map() sometimes is a good idea to use.

Map

Map is a built-in function that executes a function for every element of a Python's iterable (list, set, tuple, dictionary).

Here is a blueprint for a map: map(function_to_apply, list_of_inputs).

I have a list of numbers and I want to square every single element of that list. A lot of people would write this code below:

numbers = [1, 2, 3, 4, 5]
squared_numbers = []

for number in numbers:
    squared_numbers.append(number ** 2)

Write this code above is not bad or incorrect, but check how this code looks like when we use map() instead of a convencional for loop:

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))

If you don't want to use lambda, feel to create a normal function with def and pass the reference to that function in the lambda place.

def raise_to_second_power(number):
    return number ** 2

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(raise_to_second_power, numbers))
squared_numbers

Filter

Filter is a built-in function that will filter an iterable based on the boolean operation that we going to pass. In the case where the boolean is True for the element, we will consider that element in the new filtered list, set or some iterable. Everything is going to make sense once we go throught the examples.

Example:

I have a list of numbers and I want to write a program that filters this list to obtain just the positive numbers.

You could write this program like this:

numbers = [-2, -3, 4, 5, 10, -110, -6]
positive_numbers = []

for number in numbers:
    if number > 0:
        positive_numbers.append(number)

But, using filter(), we get this:

numbers = [-2, -3, 4, 5, 10, -110, -6]
positive_numbers = list(filter(lambda x: x > 0, numbers))

It looks like a map, but we need a boolean in order to filter the iterable.

Once again, if you don't want to use lambda, feel free to use a normal function with def.

def is_positive(number):
    return number > 0

numbers = [-2, -3, 4, 5, 10, -110, -6]
positive_numbers = list(filter(is_positive, numbers))

References from Python Docs

22