Python filter() is a built-in function that lets you process an iterable (like a list) and create a new one containing only the elements that pass a specific condition. It’s like using a sieve to sift through your data and keep only what you need. This function helps clean up or extract targeted information from your datasets.
@filter()
Syntax
new_iterable = filter(function, iterable)
new_iterable
: This is the variable where the filtered result will be stored.filter
: This is the function that filters.function
: Determines the filtering condition (e.g., “is it an even number?”). It can be a named function or a lambda function.iterable
: Sequence of elements you want to filter (e.g., a list, tuple, or string).
Example 1: Python filter()
# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Function that filters out even numbers
def even(number):
if(number % 2 == 0):
return True
else:
return False
# Filter even numbers
even_numbers = filter(even, numbers)
# Print the even numbers
print(list(even_numbers))
Code Explanation
- Line 2: Defines a list named
numbers
containing integers from 1 to 10. - Line 5-9: Defines a function named
even
that checks if a number is even. - Line 12: Applies the
even
function to each element in thenumbers
list and creates a filter objecteven_numbers
containing only the even numbers. - Line 15: Converts the filter object
even_numbers
to a list and prints the list of even numbers.
Output
[2, 4, 6, 8, 10]
Example 2: Filter Vowels From List
# List of letters
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# Function that filters out vowels
def filter_vowels(letter):
vowels = ['a', 'e', 'i', 'o', 'u']
if(letter in vowels):
return True
else:
return False
# Filter the vowels
filtered_vowels = filter(filter_vowels, letters)
# Print the filtered vowels
print(list(filtered_vowels))
Code Explanation
- Line 2: Defines a list named
letters
containing the letters of the alphabet. - Line 5-10: Defines a function named
filter_vowels
that checks if a letter is a vowel. - Line 13: Applies the
filter_vowels
function to each element in theletters
list and creates a filter objectfiltered_vowels
containing only the vowels. - Line 16: Converts the filter object
filtered_vowels
to a list and prints the list of filtered vowels.
Output
[‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
Example 3: Python filter()
With Lambda
# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Filter even numbers
even_numbers = filter(lambda x: x % 2 == 0, numbers)
# Print the even numbers
print(list(even_numbers))
Code Explanation
- Line 2: Defines a list named
numbers
containing integers from 1 to 10. - Line 5: Uses a lambda function to filter even numbers from the list. The lambda function
lambda x: x % 2 == 0
checks if a number is even. This creates a filter objecteven_numbers
containing only the even numbers. - Line 8: Converts the filter object
even_numbers
to a list and prints the list of even numbers.
Output
[2, 4, 6, 8, 10]
Example 4: Using None as a Function Inside filter()
# Random list
random_list = [1, 'a', 0, False, True, '0']
# Filter the truthy values
filtered_list = filter(None, random_list)
# Print the filtered values
print(list(filtered_list))
Code Explanation
- Line 2: Defines a list named
random_list
containing different data types. - Line 5: Uses
None
as the function argument to filter out falsy values (0, False, empty string, etc.) from the list, which creates a filter objectfiltered_list
. - Line 8: Convert the filter object
filtered_list
to a list and prints the list of filtered values.
Output
[1, ‘a’, True, ‘0’]
Example 5: Filtering a Dictionary
# Dictionary of students
students = {
'John': 85,
'Jane': 92,
'David': 78,
'Emily': 95
}
# Filter students with scores above 90
high_achievers = dict(filter(lambda item: item[1] > 90, students.items()))
# Print the high achievers
print(high_achievers)
Code Explanation
- Line 2-7: Defines a dictionary named
students
where keys are student names and values are their scores. - Line 10: Filters the dictionary items.
students.items()
returns key-value pairs. The lambda functionlambda item: item[1] > 90
checks if the second element of each pair (the score) is greater than 90. Thefilter
function applies this condition, creating an iterable of key-value pairs for students with scores above 90.dict()
converts this back into a dictionary, stored ashigh_achievers
. - Line 13: Prints the
high_achievers
dictionary.
Output
{‘Jane’: 92, ‘Emily’: 95}