Python has a handy built-in function called “filter” that allows you to sift through a list and extract specific items based on certain conditions. Let me show you a couple of examples to make it understandable.
Table of contents

Filter List In Python: Best Examples
Check out these amazing examples that showcase how the filter function in Python can be applied in real-life situations.
Check the First Letter Of Each Item In the List
Here’s an example that filters the True condition values. It prints in output only items having the first letter starting with “a.”
In the below example, we have defined a function initial_a. The logic in the for loop checks each item of the list for the first letter a. If the first letter is ‘a’, it sets to True. Otherwise, it is set to False. The filter function takes two arguments. The first argument is the function, and the second is the list (iterable). Check out the link on the filter function from Python docs.
def initial_a(mylist):
for x in mylist:
if str.lower(x[0]) == "a": # normalize the case of the
# first letter and look for 'a'
return True
else:
return False
names=['akimet','bike','apple','cat','latha']
print(names)
# extract the True results from the initial_h function to a new filter object
names_filtered = filter(initial_a,names)
print(type(names_filtered))
# convert the filter object to a list object
names_filtered_list = list(names_filtered)
print(type(names_filtered_list))
print(names_filtered_list)
As a result, the output has values only True conditions. It has printed two items, which have the first letter starting with a.
['akimet', 'bike', 'apple', 'cat', 'latha']
<class 'filter'>
<class 'list'>
['akimet', 'apple']
** Process exited - Return Code: 0 **
Press Enter to exit terminal
Filter Out Odd Numbers From A List
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(filtered_numbers)
The output will be:
[2, 4, 6, 8, 10]
** Process exited - Return Code: 0 **
Press Enter to exit terminal
Filter Out Strings With Length Greater Than 5
words = ["apple", "banana", "cat", "dog", "elephant", "fish"]
filtered_words = list(filter(lambda x: len(x) <= 5, words))
print(filtered_words)
The output will be:
['apple', 'cat', 'dog', 'fish']
** Process exited
- Return Code: 0 **
Press Enter to exit terminal
Filter Out Elements From Dictionary
students = [
{"name": "John", "age": 18},
{"name": "Jane", "age": 21},
{"name": "Bob", "age": 17},
{"name": "Alice", "age": 20},
]
filtered_students = list(filter(lambda x: x["age"] >= 18, students))
print(filtered_students)
The output will be:
[{'name': 'John', 'age': 18}, {'name': 'Jane', 'age': 21}, {'name': 'Alice', 'age': 20}]
** Process exited - Return Code: 0 **
Press Enter to exit terminal
References







You must be logged in to post a comment.