Skip to main content

Python filter() Function

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:

ParameterConditionDescription
functionRequiredA Function to be run for each item in the iterable
iterableRequiredThe 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

# Function to test if a number is even
def is_even(n):
return n % 2 == 0

# Use filter() to get only the even numbers from a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(is_even, numbers)

# Convert the filter object to a list and print the result
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']

# a function that returns True if letter is vowel
def filter_vowels(letter):
vowels = ['a', 'e', 'i', 'o', 'u']
if letter in vowels:
return True
else:
return False

# selects only vowel elements
filtered_vowels = filter(filter_vowels, letters)

# converting to tuple
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'

# Define a function to test if a string starts with 'p'
def starts_with_p(s):
return s[0].lower() == 'p'

# Use filter() to get only the words starting with 'p' from a list
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]

# the lambda function returns True for even numbers
even_numbers_iterator = filter(lambda x: (x%2 == 0), numbers)

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

output

[2, 4, 6, 8, 10]
note

In the above example, the lambda function returns True only for even numbers. Hence, the filter() function returns an iterator containing even numbers only.

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)

# converting to list
filtered_list = list(filtered_iterator)

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

output

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

1, 'a' , True and '0' are considered True on conversion to booleans