Python: How to Filter List Best Example

Filter is built-in function in python. Here’re examples that explain filtering items from list by condition.

Python filter list example

Here’s an example that filters the True condition values. It prints in output only items having the first letter starting with “a.”

Python filter function

 In the below example, we have defined a function initial_a. The logic in for loop checks each item of the list for the first letter a. If the first letter is ‘a’, it sets to True. Else it sets 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 a list (dictionary) based on a certain condition.

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

Related

Related books

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.