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.

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.

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.

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:

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: