Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Python Filter Function
2.1.
Syntax
2.2.
Arguments
2.3.
Return Value
3.
Working of Python filter() Function
3.1.
Code in Python
3.2.
Time Complexity Analysis
3.3.
Space Complexity Analysis
4.
Working of Python filter() Function with Lambda Functions
4.1.
Code in Python
4.2.
Time Complexity Analysis
4.3.
Space Complexity Analysis
5.
Working of Python filter() Function with None
5.1.
Code in Python
5.2.
Time Complexity Analysis
5.3.
Space Complexity Analysis
6.
Applications of Filter in Python
6.1.
Examples of Filter in Python
6.2.
Python
6.3.
Python
6.4.
Python
7.
Frequently Asked Questions
7.1.
What is the filter function in Python?
7.2.
What does the filter () function do?
7.3.
What is the filter like function in Python?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Python filter() Function

Author Kartik Singh
0 upvote
gp-icon
Basics of python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Hello Ninjas, we know that Python is the most versatile programming language. Python provides many in-built libraries and functions. These in-built Python functions are easy to use. They help us to code problems with less effort and clean codes.

python-filter-function

One popular Python In-Built function is Python's filter() function.

In this article, we will learn more about this Python filter function. We will discuss the syntax related to these functions. We will also see the implementation Python filter function.

Check out this article - Swapcase in Python and  Convert String to List Python.

Python Filter Function

The filter function in Python works as filters. They filter the elements of the iterable in Python, like - tuples, lists, dictionaries, etc. The condition on which the filter is done is given in the filter function. The condition defined by the function is checked for each element of the iterabel. The function returns a boolean value, true if the elements are satisfied as per the function, false otherwise.

Syntax

filter(function, sequence)

 

The filter is the keyword that tells the compiler the use of the filter function here.

Arguments

  • The sequence is the iterable object that is filtered. These iterable can be a list, set, tuple, etc. 
     
  • The function contains the parameters on which the sequence elements are filtered. It is a function with the boolean type return value.

Return Value

The return value for the Python filter function is an iterator. This iterator points to the elements of the filtered iterable object.

Also see, Python Operator Precedence

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Working of Python filter() Function

In the following code, we can understand the working of the Python filter function. The following is a code for filtering the consonants from a list of letters.

Code in Python

# sequence of letters 
letters = ['f', 'r', 'e', 'i', 'o', 'k', 't', 'p', 'q']

# function that filters consonants

def consonent_filter(sequence):
    vowels = ['a', 'e', 'i', 'o', 'u']
    if sequence in vowels:
        return False
    else:
        return True


# Using the filter function

temp = filter(consonent_filter, letters)

# converting to tuple

result = tuple(temp)
print (result)

 

Output

('f', 'r', 'k', 't', 'p', 'q')

 

In this code, the consonent_filter is used as a filter. This filters out the consonants from the letter sequence given. Here, each letter of the sequence is passed to the consonent_filter function. It returns a boolean value depending on the letter. If 'False,' the letter is filtered out of the sequence. The return value to the filter is an iterator. The iterator is converted to a tuple, and the result is printed.

Time Complexity Analysis

The above code has a filter that iterates over the entire sequence of letters. It has a complexity of O(n), where n is the number of elements in the sequence. The function that filters has a constant time complexity O(1). The total time complexity of the above code is O(n).

Space Complexity Analysis

The above program uses a tuple to store the result. In the worst case, all the elements can pass the filter. Therefore the overall space complexity of the above code is O(n).

Working of Python filter() Function with Lambda Functions

The Python filter function can use the lambda function as an argument. The Lambda function in Python is an anonymous function without defined names. The lambda keyword defines an anonymous function. 

The following code explains the use of the lambda function with filter in Python. 

This code is the implementation to find buzz numbers from a given sequence. A buzz number is a number that is either divisible by seven or ends in 7.

Code in Python

# The given sequence of numbers

sequence = [17, 21, 3, 47, 5, 6, 77, 23, 71, 91]

# The lambda function returns True for even numbers

iterator = filter(lambda x: x % 7 == 0 or x % 10 == 7, sequence)

# Converting to a list

buzz_numbers = list(iterator)

print (buzz_numbers)


Output

[17, 21, 47, 77, 91]


In this code, the lambda function is used as a filter. Here, each number of the sequence is passed to the lambda function. It returns a boolean value depending on the number. The number is checked for divisibility with seven or the last digit as 7. If 'False,' the number is filtered out of the sequence. The return value to the filter is an iterator. The iterator is converted to a list, and the result is printed.

Time Complexity Analysis

The above code has a filter that iterates over the entire sequence of numbers. It has a complexity of O(n), where n is the number of elements in the sequence. The lambda function has a constant time complexity O(1). The total time complexity of the above code is O(n).

Space Complexity Analysis

The above program uses a list to store the result. In the worst case, all the elements can pass the filter. Therefore the overall space complexity of the above code is O(n).

Working of Python filter() Function with None

The Python filter function can work with None passed as an argument. In this case, all the sequence elements corresponding to a true value will be kept in the result. The elements corresponding to a true value are positive real numbers, True, String, chars, etc.

Here is a code for implementing the None in Python filter function.

Code in Python

# random list

random_list = [1.5, 'c', 7, False, True, '0',0,"coding-ninjas",1]

iterator = filter(None, random_list)

# converting to a list

result = list(iterator)

print (result)


Output

[1.5, 'c', 7, True, '0', 'coding-ninjas', 1]


Here, we do not have any function as an argument. As a result, all the sequence elements corresponding to a true value are included in the result. The truth correspondence here means the value that would give true when typecasted to a boolean.

Time Complexity Analysis

The above code has a filter that iterates over the entire sequence of numbers. It has a complexity of O(n), where n is the number of elements in the sequence. Here we have no function, so the true value comparison is O(1) time operation. The total time complexity of the above code is O(n).

Space Complexity Analysis

The above program uses a list to store the result. In the worst case, all the elements can pass the filter. Therefore the overall space complexity of the above code is O(n).

Applications of Filter in Python

The filter() function in Python is used to filter elements from an iterable (like a list, tuple, or set) based on a given function or condition. Here are some common applications:

  • We can use filter() to select elements that satisfy a specific condition defined by a custom function. For example, filtering a list to include only even numbers.
  • It is a handy for removing elements that evaluate to False or None.
  • We can use filter() to select elements based on their length.
  • It eliminates duplicates by applying filter() with a set.
  • We can use filter() with a predefined function to encapsulate complex criteria.
  • For a list of objects, use filter() to select elements based on specific attributes.

Examples of Filter in Python

Here are some examples of using the filter() function in Python:

Example 1: Filter Even Numbers

  • Python

Python

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)

Output

output

Example 2: Filter Positive Numbers

  • Python

Python

numbers = [-3, -2, -1, 0, 1, 2, 3]
positives = list(filter(lambda x: x > 0, numbers))
print(positives)

Output

output

Example 3: Filter Words with Length Greater Than 5

  • Python

Python

words = ['apple', 'banana', 'kiwi', 'orange', 'grape']
long_words = list(filter(lambda x: len(x) > 5, words))
print(long_words)

Output

output

Frequently Asked Questions

What is the filter function in Python?

The filter() function in Python is a built-in function that filters elements from an iterable based on a specified function or condition.

What does the filter () function do?

The filter() function creates an iterator of elements for which a specified function returns True.

What is the filter like function in Python?

There are functions like map() and reduce() like filter in Python.

Conclusion

In this article, we learned about the Python filter function. We saw the syntax followed by the filter function. We also learned about the working of the Python filter function. We saw how they work when passed with different types of functions as arguments. We learned the working of filter functions with default, lambda, and None functions. We also discussed the time and space complexity of the filter function under the above three approaches.

To learn more about Python filter function, you can check out our other blogs:


Check out some amazing Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Basics of C, Basics of Java, etc., along with some Contests and Interview Experiences only on Coding Ninjas Studio

Check out The Interview Guide for Product Based Companies and some Popular Interview Problems from Top Companies, like  Amazon, Adobe, Google, etc., on Coding Ninjas Studio.

Guided path
Free
gridgp-icon
Basics of python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass