How to Filter a List in Python?

Python Tutorials

Filtering a list means keeping only those items in the list that statisfy a particular condition. For example, filtering [1, 2, 3, 4, 5, 6] for even numbers will result in [2, 4, 6].

In Python, you can filter a list in the following ways.

Use For Loop to Filter List

Use for loop to iterate over the items of the list and create a new list with items that satisfy the given condition.

numbers = [1, 2, 3, 4, 5, 6]
even = []

for x in numbers:
    if x%2 == 0:
        even.append(x)
        
print(even)
# [2, 4, 6]

Use List Comprehension to Filter List

Use the list comprehension syntax [item for item in list if condition] with list and condition to filter the items that statify the given condition.

numbers = [1, 2, 3, 4, 5, 6]
even = [item for item in numbers if item%2 == 0]
        
print(even)
# [2, 4, 6]

Use filter() to Filter List

Call the filter(function, list) function with list and function to get iterable containing items from the given list for which the function returns True.

Call the list(itreable) with iterable as the parameter to construct the new list.

def isEven(num):
    return num%2 == 0
    
numbers = [1, 2, 3, 4, 5, 6]

iterable = filter(isEven, numbers)

print(list(iterable))
# [2, 4, 6]

Leave a Reply

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