How to use filter function in Python

In this Python tutorial, we will discuss several methods to use a filter function in Python. Moreover, we’ll look at various examples to use a filter function in Python.

Recently, I have been working on a machine learning project and I have found that it requires a filter function.

Here we will learn

  • How to use a filter function in Python
  • How to use a filter function in Python using lambda function
  • How to use a filter function in Python using list comprehension
  • How to use a filter function in Python using re.match()
  • How to use a filter function in Python using for loop
  • How to use a filter function in Python using reduce()

How to use a filter function in Python

  • In this section, we will discuss How to use a filter function in Python.
  • The filter() method makes functional programming in Python easier. It accepts an iterable and a function as arguments, and it applies the function supplied to each element of the iterable. An iterable is returned once this is finished.
  • You can use the filter() function, for instance, to separate the odd and even components of a list of numbers into two independent sets. It can even be used to select dictionaries based on their keys from a list of dictionaries.

Syntax:

Let’s have a look at the syntax and understand the working of filter() function in Python.

filter(function, iterable)
  • It consists of a few parameters
    • function: It is used to determine whether or not each iterable element is true for this function.
    • iterable: sets, lists, tuples, and other iterables on which filtering will be done.

Example:

Let’s take an example and check how to use a filter function in Python.

Source Code:

new_val = [67, 93, 28, 17, 48]

# Creating a function 
def filtered_val(val):
  if val >= 29 :
     return True

new_result = filter( filtered_val, new_val)
print(list(new_result))

In the following given code first we declared a list ‘new_val’ and then defined a function ‘filtered_val’ and set the condition if value is greater than 29 then it will filter all the values and return [67, 93, 48].

Here is the Screenshot of the following given code

Use of filter function in Python
Use of filter function in Python

This is how to use a filter function in Python.

Read: How to access items of a tuple in Python

How to use a filter function in Python using lambda function

  • Now let us understand How to use a filter function in Python using a lambda
  • By using a lambda function, procedure four (the filter() method) can be reduced to a single line.
  • We can use lambda to write the condition inside the ‘filter()’ function rather than constructing a new value function separately.
  • In this instance, filtering the variable whose new value will be divided by six is done, and the filtered iterator is then turned into a list.

Example:

new_values = [18, 54, 26, 36, 12, 1]
# Returns the elements which are multiples of 6
new_result = list(filter(lambda n : n%6 == 0, new_values))
print(new_result)

In the above code first, we created a list ‘new_values’ and then used list function within this function we used lambda and set the condition if the number is divided by 6 then it will store the value in the new list.

You can refer to the below Screenshot.

How to use a filter function in Python using lambda function
How to use a filter function in Python using lambda function

As you can see in the Screenshot we have discussed how to use a filter function in Python using the lambda function.

Read: Calculate the exponential value of a number in Python

How to use a filter function in Python using list comprehension

  • Now let us discuss how to use a filter function in Python using list comprehension.
  • The use of for loop and if-else conditions on lists is a creative technique. One line of code can be used to implement method one.
  • In this instance, we are iterating through all of the list items in the loop and choosing the score that is higher than or equal to 1800.
  • It is simple to write, and you can easily include several if-else statements.

Example:

Let’s take an example and check how to use a filter function in Python using list comprehension.

Source Code:

Zip_code_USA = [6723, 9212, 14562, 9546, 1845, 9456]

new_output = [i for i in Zip_code_USA if i >= 1800]

print(new_output)

In the following given code first we declared a list ‘Zip_code_USA’ and then used the list comprehension to iterate through all of the list items in the loop and choosing the score that is higher than or equal to 1800.

Here is the implementation of the following given code

How to use a filter function in Python using list comprehension
Using list comprehension along with filter function

In this example, we have understood how to use a filter function in Python using list comprehension.

Read: Fibonacci series in Python

How to use a filter function in Python using re.match()

  • In this section, we will discuss how to use a filter function in Python using re.match().
  • The re.match() method in Python locates and returns the first instance of a regular expression pattern. The Regex Match function in Python only looks for a matching string at the start of the text that is being searched.
  • If one match is discovered in the first line, the corresponding object is created. The Python Regex Match method returns null if a match is found in a subsequent line.
  • In this instance, list comprehension is being used to filter out names that begin with “N” by passing a regex pattern of “N.*” to the re.match()’ function.

Example:

Here we will take an example and check how to use a filter function in Python using re.match().

Source Code:

import re

Country_name = ["USA", "Germany", "Australia", "China"]

# regex pattern
new_patt = "A.*"

# Match the above pattern using list comprehension
new_result = [i for i in Country_name  if re.match(new_patt, i)]

print(new_result)

In the following given code first, we imported the list ‘Country_name’ and then match the above pattern using list comprehension. If the given input character will match with the input list elements then it will return the particular item.

You can refer to the below Screenshot.

How to use a filter function in Python using re.match_
How to use a filter function in Python using re.match()

This is how to use a filter function in Python using re.match().

Read: How to convert a dictionary into a string in Python

How to filter the values in Python using for loop

  • In this section, we will discuss how to use a filter function in Python using for loop.
  • We will traverse the list and choose the elements that satisfy the particular condition using the for loop and if-else commands. We shall in this instance eliminate any gains that are larger than or equal to 100.
  • With this technique, a new list is made and the filtered value is added to it. It is a quick approach to filter the list, but it is ineffective.

Example:

Let’s take an example and check how to use a filter function in Python using for loop.

Source Code:

student_age = [24, 27, 19, 17, 19, 21]

new_list = []

for i in student_age:
    if i >= 20:
        new_list.append(i)

print(new_list)

In the following given code first, we declared a list ‘student_age’ and then defined an empty list. Next, we will iterate the values and set the condition if i is greater than 20 then it will filter all the values and return them to the new list.

Here is the Screenshot of the following given code.

How to use a filter function in Python using for loop
Filter values by using for loop condition

As you can see in the Screenshot we have discussed how to use a filter function in Python using for loop.

Read: How to Check if a Key Exists in a Python Dictionary

How to use a filter function in Python using Filter With None as a Function Parameter

  • Here we will discuss how to use a filter function in Python using Filter With None as a Function Parameter.
  • Any element that the filter method determines to be false will be removed from the iterable if None is used as the function argument. These elements include, for instance, empty strings, 0, and empty braces, as well as the boolean False.

Example:

Let’s take an example and check how to use a filter function in Python using Filter With None as a Function Parameter.

Source Code:

new_values = [89, -17, "", False, False, 1, 1.1, {}, []]

new_result = filter(None, new_values)

for i in new_result:

   print("Filter values :",i)

You can refer to the below Screenshot

How to use a filter function in Python using Filter With None as a Function Parameter
How to use a filter function in Python using Filter With None as a Function Parameter

This is how to use a filter function in Python using Filter With None as a Function Parameter.

Read: How to Create a Dictionary from one list in Python

How to use a filter function in Python using reduce()

  • In this section, we will discuss how to use a filter function in Python using reduce().
  • Reduce is a built-in function that reduces an iterable to a single continuous value, making it another functional programming tool. Reduction or folding are other names for such a process.

Syntax:

Let’s have a look at the Syntax and understand how to use a filter function in Python using reduce().

reduce(function, iterable, initial)

Let’s look at an example where the filter and reduce are used to add up all the odd integers in a list. See the illustration below:

Example:

from functools import reduce

odd_num = [16, 28, 1, 13, 19, 21, 25, 31, 39, 10]

# using reduce and filter function
result= reduce(lambda i, z: i + z, filter(lambda i: i%3==0, odd_num))

# Display the content
print(result) 

In the above code first we will import the reduce module and then used the reduce and filter function.

Here is the implementation of the following given code

How to use a filter function in Python using reduce
Using reduce to filter the values in Python

You may also like to read the following Python tutorials.

In this article, we have discussed several methods to use a filter function in Python. And also we have covered the following given topics.

  • How to use a filter function in Python
  • How to use a filter function in Python using lambda function
  • How to use a filter function in Python using list comprehension
  • How to use a filter function in Python using re.match()
  • How to use a filter function in Python using for loop
  • How to use a filter function in Python using reduce()