Open In App

filter() in python

Last Updated : 20 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. 

Python filter() Syntax

The filter() method in Python has the following syntax:

Syntax: filter(function, sequence)

Parameters:

  • function: function that tests if each element of a sequence is true or not.
  • sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators.

Returns: an iterator that is already filtered.

Python filter Function Examples

Let us see a few examples of the filter() function in Python.

Python Filter Function with a Custom Function

In this example, we are using the filter function along with a custom function “fun()” to filter out vowels from the Python List.

Python
# function that filters vowels
def fun(variable):
    letters = ['a', 'e', 'i', 'o', 'u']
    if (variable in letters):
        return True
    else:
        return False


# sequence
sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']

# using filter function
filtered = filter(fun, sequence)

print('The filtered letters are:')
for s in filtered:
    print(s)

Output:

The filtered letters are:
e
e

Filter Function in Python with Lambda

Python filter() function is normally used with Lambda functions. In this example, we are using the lambda function to filter out the odd and even numbers from a list.

Python
# a list contains both even and odd numbers. 
seq = [0, 1, 2, 3, 5, 8, 13]

# result contains odd numbers of the list
result = filter(lambda x: x % 2 != 0, seq)
print(list(result))

# result contains even numbers of the list
result = filter(lambda x: x % 2 == 0, seq)
print(list(result))

Output:

[1, 3, 5, 13]
[0, 2, 8]

Filter Function in Python with Lambda and Custom Function

In this program, we will use both a custom function “is_multiple_of_3()” as well as a lambda function. The filter() function is used to apply this function to each element of the numbers list, and the lambda function is used to iterate over each element of the list before applying the condition. This way, we can perform additional operations on each element before applying the condition.

Python
# Define a function to check 
# if a number is a multiple of 3
def is_multiple_of_3(num):
    return num % 3 == 0


# Create a list of numbers to filter
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use filter and a lambda function to
# filter the list of numbers and only
# keep the ones that are multiples of 3
result = list(filter(lambda x: is_multiple_of_3(x), numbers))

# Print the result
print(result)

Output
[3, 6, 9]

Time complexity analysis

  1. The filter function is used to filter the list of numbers, and it applies the lambda function to each element of the list. The time complexity of the filter function is O(n), where n is the number of elements in the list.
  2. The time complexity of the lambda function is constant, O(1), since it only performs a single arithmetic operation. Therefore, the overall time complexity of the program is O(n).

Auxiliary Space analysis

The program uses a list to store the filtered numbers, so the space complexity is proportional to the number of filtered numbers. In the worst case, if all numbers are multiples of 3, the filtered list will have n/3 elements. Therefore, the space complexity is O(n/3), which simplifies to O(n) in big O notation.

filter() in python – FAQs

What does the filter() function do?

The filter() function in Python filters elements from an iterable (like a list) based on a function (or None for truthy values). It returns an iterator that yields those elements for which the function returns True.

How does reduce() and filter() work in Python?

  • filter(): Filters elements from an iterable based on a function.
  • reduce(): Applies a function to the items of an iterable, cumulatively, from left to right, so as to reduce the iterable to a single value.

Both functions are part of Python’s functools module (Python 3.x) and can be used together to filter and then reduce data if needed.

How to filter a list in Python?

To filter a list in Python, you can use a list comprehension or the filter() function along with a lambda function or a defined function.

Using list comprehension:

# Example using list comprehension
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
filtered_numbers = [num for num in numbers if num % 2 == 0]
print(filtered_numbers) # Output: [2, 4, 6, 8]

Using filter() with a lambda function:

# Example using filter() with lambda function
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
filtered_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(filtered_numbers) # Output: [2, 4, 6, 8]

How to filter an object in Python?

Filtering an object in Python typically involves filtering its attributes or properties based on certain conditions. Here’s an example using filter() and a lambda function to filter a list of objects based on an attribute:

# Example filtering objects based on attribute
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
people = [
Person('Alice', 25),
Person('Bob', 30),
Person('Charlie', 22)
]
# Filter people older than 25
filtered_people = list(filter(lambda person: person.age > 25, people))
for person in filtered_people:
print(person.name, person.age)

How to filter a text in Python?

Filtering text in Python usually involves searching for specific patterns or conditions within strings. Here’s an example using list comprehension to filter out words containing a specific substring:

# Example filtering text using list comprehension
text = "Python is awesome and versatile"
filtered_words = [word for word in text.split() if 'o' in word]
print(filtered_words) # Output: ['Python', 'awesome']


Previous Article
Next Article

Similar Reads

Spatial Filters - Averaging filter and Median filter in Image Processing
Spatial Filtering technique is used directly on pixels of an image. Mask is usually considered to be added in size so that it has a specific center pixel. This mask is moved on the image such that the center of the mask traverses all image pixels.In this article, we are going to cover the following topics - To write a program in Python to implement
3 min read
Filter Python list by Predicate in Python
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method Syntax: filter(predicate, list) where, list
2 min read
Filter List of Python Dictionaries by Key in Python
Filtering a list of dictionaries in Python based on a specific key is a common task in data manipulation and analysis. Whether you're working with datasets or dictionaries, the ability to extract relevant information efficiently is crucial. In this article, we will explore some simple and commonly used methods to filter a list of dictionaries in Py
3 min read
Filter Pandas dataframe in Python using 'in' and 'not in'
The in and not in operators can be used with Pandas DataFrames to check if a given value or set of values is present in the DataFrame or not using Python. The in-operator returns a boolean value indicating whether the specified value is present in the DataFrame, while the not-in-operator returns a boolean value indicating whether the specified valu
3 min read
Lambda and filter in Python Examples
Prerequisite : Lambda in Python Given a list of numbers, find all numbers divisible by 13. Input : my_list = [12, 65, 54, 39, 102, 339, 221, 50, 70] Output : [65, 39, 221] We can use Lambda function inside the filter() built-in function to find all the numbers divisible by 13 in the list. In Python, anonymous function means that a function is witho
2 min read
Intersection of two arrays in Python ( Lambda expression and filter function )
Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun
1 min read
Python - Filter immutable rows representing Dictionary Keys from Matrix
Given Matrix, extract all the rows which has elements which have all elements which can be represented as dictionary key, i.e immutable. Input : test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5:4}, 3, "good"], [True, "best"]] Output : [['gfg', 1, (4, 4)], [True, 'best']] Explanation : All elements in tuples are immutable. Input : test_list =
7 min read
Python | Filter a list based on the given list of strings
Given a List, the task is to filter elements from list based on another list of strings. These type of problems are quite common while scraping websites. Examples: Input: List_string1 = ['key', 'keys', 'keyword', 'keychain', 'keynote'] List_string2 = ['home/key/1.pdf', 'home/keys/2.pdf', 'home/keyword/3.pdf', 'home/keychain/4.pdf', 'home/Desktop/5.
3 min read
Python | Filter dictionary of tuples by condition
Sometimes, we can have a very specific problem in which we are given a tuple pair as values in dictionary and we need to filter dictionary items according to those pairs. This particular problem as use case in Many geometry algorithms in competitive programming. Let's discuss certain ways in which this task can be performed. Method #1 : Using items
3 min read
Python | Pandas dataframe.filter()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.filter() function is used to Subset rows or columns of dataframe according to labels in the specified index. Note that
2 min read
Practice Tags :