Skip to content

Python filter list by condition

  • by

Use the built-in function filter function to filter lists by the condition in Python. The filter() function returns a filter object with the filtered elements.

filter(func, elements)

List comprehension is a shorthand for looping through a list with one line of code.

[element for element in elements if condition]

Python filter list by condition example

Simple example code filter all numbers and only numbers that are higher than 25.

numbers = [25, 24, 26, 45, 25, 23, 50, 51]
filtred = list(filter(lambda x: x > 25, numbers))



Python filter list by condition

Another way is to create an empty list, iterate through the current list and append all relevant items to the new list, like so:

numbers = [25, 24, 26, 45, 25, 23, 50, 51]
new_list = []

for i in numbers:
if 25 <= i <= 50:


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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.