Skip to content

Python filter() function

  • by

Python filter() function is used to filter elements from an iterable (list, tuple, etc.) for which a function returns True. The filter() function returns an iterator.

filter(function, iterable)

Python filter() function example

For simple example code a new list with only the values equal to or above 18:

ages = [5, 10, 15, 20, 25, 30]


def myFunc(x):
    if x < 18:
        return False
    else:
        return True


adults = filter(myFunc, ages)

print(adults)
print(type(adults))
print(list(adults))

Output:

Python filter() function

Using Lambda Function Inside filter()

ages = [5, 10, 15, 20, 25, 30]

res = filter(lambda x: (x % 2 == 0), ages)

# converting to list
even_numbers = list(res)

print(even_numbers)

Output: [10, 20, 30]

Do comment if you have any doubts or suggestions on this Python basics function topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading