Skip to content

Python filter() Function

Learn how to use Python's filter() function to create iterators containing only elements that meet a condition, with syntax, parameters, examples, and lambda usage.

The filter() function returns an iterator where the items are filtered through a function to test if the item is accepted or not.

Syntax

filter(function, iterable)

filter() Parameters

Python filter() function parameters:

Parameter Condition Description
function Required A Function to be run for each item in the iterable
iterable Required The iterable to be filtered

filter() Return Value

Python filter() function returns an iterator yielding the items of the iterable for which the function returns True.

Examples

Example 1: filter even numbers from List

def is_even(n):
    return n %  2 ==  0

numbers = [1,  2,  3,  4,  5,  6, 7, 8, 9, 10]
even_numbers = filter(is_even, numbers)

print(list(even_numbers))  # Output: [2,  4,  6]

output

[2, 4, 6]

Example 2: filter vowels from List

letters = ['a', 'b', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

def filter_vowels(letter):
    vowels = ['a', 'e', 'i', 'o', 'u']
    if letter in vowels:
        return True 
    else:
        return False

filtered_vowels = filter(filter_vowels, letters)

vowels = tuple(filtered_vowels)
print(vowels)   # Output: ('a', 'e', 'i', 'o', 'u')

output

('a', 'e', 'i', 'o', 'u')

Example 3: filter words string that starts with 'p'

def starts_with_p(s):
    return s[0].lower() == 'p'

words = ["python", "java", "c++", "perl", "pascal"]
p_words = filter(starts_with_p, words)  # Output: ['python', 'pascal']

output

['python', 'pascal']

Example 4: filter() function with Lambda

You can also use the Python filter() function with the lambda function.

For example:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers_iterator = filter(lambda x: (x%2 == 0), numbers)

even_numbers = list(even_numbers_iterator)
print(even_numbers)     # Output: [2, 4, 6, 8, 10]

output

[2, 4, 6, 8, 10]

Example 5: use None as a Function inside filter() function

When None is used as the first argument to the filter() function, it extracts all elements that evaluate to True when converted to boolean.

For example:

random_list = [1, 'a', 0, False, True, '0']
filtered_iterator = filter(None, random_list)

filtered_list = list(filtered_iterator)

print(filtered_list)    # Output: [1, 'a', True, '0']

output

[1, 'a', True, '0']
Navigation