Skip to content

Python filter list

  • by

You can filter lists based on specified criteria using the filter() function in Python. You can also Filter the list elements using for loop, list comprehension, regex, and lambda functions.

filter(fn, list)

Python filter list example

Simple example code filter list using the for loop and if-else statements.

profits = [200, 400, 90, 50, 20, 150]

res = []

for p in profits:
    if p >= 100:
        res.append(p)

print(res)
print(type(res))

Output:

Python filter list example

Using List Comprehension

This translates method one into a single line of code.

scores = [200, 105, 18, 80, 150, 140]

res = [s for s in scores if s >= 150]

print(res)

Using regex

import re

students = ["Abid", "Natasha", "Nick", "Matthew"]

# regex pattern
pattern = "N.*"

# Match pattern using list comprehension
res = [x for x in students if re.match(pattern, x)]

print(res)

Using filter() Method

The filter() is a built-in Python function to filter list items. It requires a filter function and a list.

def filter_height(height):
    if (height < 150):
        return True
    else:
        return False
  
heights = [140, 180, 165, 162, 145]
res = filter(filter_height, heights)


print(list(res))

Using Lambda Function

You can convert method four (filter() Method) into a single line by using the lambda function

ages = [20, 33, 44, 66, 78, 92]

res = filter(lambda a: a > 50, ages)

print(list(res))

Do comment if you have any doubts or suggestions on this Python filter 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

Your email address will not be published. Required fields are marked *