Different Usage of Python filter() Function

Ayushi Trivedi Last Updated : 05 Jun, 2024
4 min read

Introduction

This article delves into the syntax, essential features, and real-world uses of Python‘s filter() function, which is a flexible and strong tool. We show how to effectively handle and refine data from different iterables, including lists, tuples, and sets, using filter() with thorough explanations and original code samples. This tutorial offers a thorough rundown of Python’s filtering features, from basic usage with straightforward conditions to more intricate situations involving custom functions and lambda expressions, so that both novice and seasoned programmers may grasp them.

Python filter() function

Understanding filter() in Python

An iterator can be created from elements of an iterable for which a function returns true using Python’s built-in filter() function. The main purpose of filter() is to remove elements according to a criteria given by a function from an iterable (like lists, tuples, or sets).

Syntax

filter(function, iterable)
  • function: A function that tests if each element of an iterable returns true or false.
  • iterable: The iterable (e.g., list, tuple, set) to be filtered.

The filter() method returns an iterator (of type filter) that can be transformed into a list, tuple, or set.

Key Points

  • Filter() is a lazy function; it waits to process the elements until they are called upon.
  • When you don’t want to keep every element in memory and you have a big data set, it can be helpful.

Basic Example of filter() Function

Let’s start with a basic example to understand how filter() works:

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

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Using filter() to get even numbers
even_numbers = filter(is_even, numbers)

# Converting the filter object to a list
even_numbers_list = list(even_numbers)
print(even_numbers_list)

Output:

[2, 4, 6, 8, 10]

In this instance, the function is_even determines whether a given number is even. To exclude even integers from the numbers list, the filter() function utilizes is_even.

Using Lambda with filter()

To generate anonymous and condensed functions, you may also use a lambda function as the first argument in filter().

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Using filter() with a lambda function to get odd numbers
odd_numbers = filter(lambda x: x % 2 != 0, numbers)

# Converting the filter object to a list
odd_numbers_list = list(odd_numbers)
print(odd_numbers_list)

Output:

[1, 3, 5, 7, 9]

Filtering Strings Using filter() Function

Strings can also be filtered using a condition by using the filter() function.

# Function to check if a character is a vowel
def is_vowel(char):
    return char.lower() in 'aeiou'

sentence = "Hello, World!"

# Using filter() to get vowels from the sentence
vowels = filter(is_vowel, sentence)

# Converting the filter object to a list
vowels_list = list(vowels)
print(vowels_list)

Output:

['e', 'o', 'o']

Filtering with Complex Conditions

You can create more complex filtering conditions using filter(). Let’s filter a list of dictionaries based on multiple criteria.

students = [
    {"name": "Alice", "grade": 85},
    {"name": "Bob", "grade": 72},
    {"name": "Charlie", "grade": 90},
    {"name": "Dave", "grade": 68},
    {"name": "Eve", "grade": 95}
]

# Function to filter students with grades greater than or equal to 80
def is_passing(student):
    return student["grade"] >= 80

# Using filter() to get students with passing grades
passing_students = filter(is_passing, students)

# Converting the filter object to a list
passing_students_list = list(passing_students)
print(passing_students_list)

Output:

[{'name': 'Alice', 'grade': 85}, {'name': 'Charlie', 'grade': 90}, {'name': 'Eve', 'grade': 95}]

Filtering Unique Elements Using filter() Function

To illustrate a more complex scenario, we filter unique components from a list of tuples based on the first element of each tuple.

data = [(1, 'a'), (2, 'b'), (1, 'c'), (3, 'd'), (2, 'e')]

# Function to filter unique elements based on the first element of the tuple
def unique_first_elements(seq):
    seen = set()
    for item in seq:
        if item[0] not in seen:
            seen.add(item[0])
            yield item

# Using filter() with the unique_first_elements generator function
unique_data = unique_first_elements(data)

# Converting the generator to a list
unique_data_list = list(unique_data)
print(unique_data_list)

Output:

[(1, 'a'), (2, 'b'), (3, 'd')]

Some Practice Questions Using filter() Function

Let us now look into some practice questions using filter() function.

Filter Positive Numbers

Using the filter() function, you will construct a function in this exercise to remove positive values from a list of integers. This will clarify for you how to use fundamental filtering logic in Python with numerical data.

def filter_positive_numbers(numbers):
    return list(filter(lambda x: x > 0, numbers))

# Test the function
numbers = [-10, -5, 0, 5, 10]
positive_numbers = filter_positive_numbers(numbers)
print(positive_numbers)

Output:

[5, 10]

Filter Palindromes

By using the filter() method to develop a function that eliminates palindromic phrases from a list of strings, as demonstrated in this example, you can improve your string manipulation and logic filtering skills—which apply both forward and backward.

def filter_palindromes(words):
    return list(filter(lambda word: word == word[::-1], words))

# Test the function
words = ["level", "world", "radar", "python", "madam"]
palindromic_words = filter_palindromes(words)
print(palindromic_words)

Output:

['level', 'radar', 'madam']

Filter Custom Objects

In order to demonstrate how to filter custom objects based on properties, this assignment entails designing a Person class with attributes like name and age, and then writing a function to remove Person instances over 30 from a list using the filter() function.

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

    def __repr__(self):
        return f"{self.name} ({self.age})"

def filter_persons_over_30(persons):
    return list(filter(lambda person: person.age <= 30, persons))

# Test the function
people = [
    Person("Alice", 25),
    Person("Bob", 35),
    Person("Charlie", 30),
    Person("Dave", 40),
    Person("Eve", 28)
]

filtered_people = filter_persons_over_30(people)
print(filtered_people)

Output:

[Alice (25), Charlie (30), Eve (28)]

Conclusion

Python’s filter() method is an effective tool that can be used to process and refine data in an efficient manner. Users can apply both straightforward and intricate filtering requirements by using lambda expressions and custom functions. This article provides an extensive introduction to filter(), along with real-world examples and comprehension-boosting tasks. Filter() is a very useful tool for programmers, regardless of experience level, who want to efficiently manage and handle data in their Python programs. It may be used to filter texts, numerical data, or custom objects.

Don’t miss this chance to improve your skills and advance your career. Learn Python with us! This course is suitable for all levels.

My name is Ayushi Trivedi. I am a B. Tech graduate. I have 3 years of experience working as an educator and content editor. I have worked with various python libraries, like numpy, pandas, seaborn, matplotlib, scikit, imblearn, linear regression and many more. I am also an author. My first book named #turning25 has been published and is available on amazon and flipkart. Here, I am technical content editor at Analytics Vidhya. I feel proud and happy to be AVian. I have a great team to work with. I love building the bridge between the technology and the learner.

Responses From Readers

Clear

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details