Python List filter() with Examples

In Python, we may need to filter a list to extract specific elements based on certain criteria or conditions. The filter() function is a powerful tool in Python that simplifies the process of filtering lists. In this article, we will explore various methods and techniques for filtering lists and cover a wide range of scenarios and use cases.

Note that we can use the itertools.filterfalse() function to return elements of iterable for which the condition is false.

1. Filter a List using the ‘filter()‘ Function

The filter() function allows us to apply a condition to each element of an iterable (such as a list), retaining only those elements for which the function returns True. The syntax of the filter() function is as follows:

filter(condition, iterable)

The filter() function returns an iterator containing the elements from the iterable. We can pass the iterable to list() function again and collect the filtered elements in a new list.

filtered_elements = list( filter(condition, iterable) )

1.1. Filter a List of Numbers

Filtering a list of numbers involves selecting elements that meet specific numerical criteria. The given example filters the even numbers from the 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 program output:

[2, 4, 6, 8, 10]

1.2. Filter a List of Strings

Filtering a list of strings typically involves selecting strings that match certain patterns or criteria. In this example, we filter all strings containing the substring ‘an‘.

# List of strings
strings = ["apple", "banana", "orange", "grape", "kiwi"]

# Pattern to filter
pattern = "an"

# Use filter() with a lambda function to filter strings containing the pattern
filtered_strings = filter(lambda x: pattern in x, strings)

# Convert the filtered result to a list
filtered_strings_list = list(filtered_strings)

print(filtered_strings_list)

The program output:

['banana', 'orange', 'grape']

1.3. Filter a List of Objects

To filter a list of objects, we need to pass the condition on a certain attribute(s) in the object. The following example filters all Person objects whose age is greater than 28.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

people = [Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35)]
selected_people = list(filter(lambda x: x.age > 28, people))
for person in selected_people:
    print(person.name, person.age)

The program output:

Alice 30
Charlie 35

2. Filter a List Based on Another List

Filtering a list based on another list involves selecting elements from the first list that exist in the second list or satisfy a membership condition.

Suppose we have two lists: main_list and filter_list. We want to filter elements from main_list that exist in filter_list. The lambda function checks if each element (x) in the main_list exists in the filter_list.

# Define the main list
main_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Define the filter list
filter_list = [2, 4, 6, 8, 10]

# Filter the main list based on the filter list
filtered_list = list(filter(lambda x: x in filter_list, main_list))

# Output the filtered list
print(filtered_list)

The program output:

[2, 4, 6, 8, 10]

This approach effectively filters elements from one list based on the presence or absence of those elements in another list.

3. Filter a List by Complex Condition

To filter a list by complex condition, we must extract the condition(s) in a separate function and supply this function to filter().

Suppose we have a list of numbers and we want to filter the list so that the numbers that are greater than 5 have an even index position in the list.

# Define a function to check the complex condition
def is_complex_condition(num, idx):
    return num > 5 and idx % 2 == 0

# Define the list of numbers
numbers = [3, 8, 2, 10, 6, 4, 7, 9]

# Filter the list based on the complex condition using the filter() function
filtered_numbers = list(filter(lambda x: is_complex_condition(x[1], x[0]), enumerate(numbers)))

# Extract the numbers from the filtered result
filtered_numbers = [num for idx, num in filtered_numbers]

# Output the filtered list
print(filtered_numbers)

The program output:

[8, 10]

4. Handling None or Empty Values

Handling None or empty values in a list is a common requirement when filtering lists. To filter such values, we need to update the filter condition such that these values are excluded from the result.

The following example defines a function filter_condition that takes a value as input and returns True if the value is not None, not an empty string, and is even.

def filter_condition(value):
    return value is not None and value != "" and value % 2 == 0

# Define a list with None values and empty strings
data = [1, None, 3, None, "", 6, "", 8, 9, None]

# Filter the list based on the filter condition using the filter() function
filtered_data = list(filter(filter_condition, data))

# Output the filtered list
print(filtered_data)

The program output:

[6, 8]

5. Conclusion

In this example, we learned to use the filter() function which provides a concise and readable way to filter elements from a list based on a specified condition. It simplifies the code and improves its readability compared to using list comprehension.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.