AppDividend
Latest Code Tutorials

Python Filter Function Tutorial With Example | Python Standard Library

0 26

Get real time updates directly on you device, subscribe now.

Python Filter Function Tutorial With Example is today’s topic. The filter() function returns an iterator where the items are filtered through a function to test if the item is accepted or not. Python filter() method filters the given iterable with the help of a function that tests each item in the iterable to be true or not. The filter() method constructs the iterator from items of an iterable for which a function returns true.

Python Filter Function Tutorial

The syntax for Python Filter function is following.

filter(function, iterable)

The function parameter is to be run for each item in the iterable. The function that tests if elements of the iterable return True or False. If None, then the function defaults to Identity function which returns False.

An iterable is the parameter to be filtered. An iterable which is to be filtered could be Python Data Structure like sets, lists, tuples, or containers of any iterators.

See the following example of Python Filter method.

# app.py

nums = [21, 19, 18, 46, 6, 29]
def checkEven(x):
  if x % 2 == 0:
    return True
  else:
    return False

data = filter(checkEven, nums)
print(list(data))

In the above code, we have defined a list anda function which takes one parameter and check that item if it is even. If it is true then it will return true, and we will get that item in the data object, and then we can convert it to the list.

The filter() method then passes each integer to the checkEven() method to check if it returns True or False. In the end, it creates the iterator of the ones that return true.

See the output below.

 

Python Filter Function Tutorial

Lambda and Filter function in Python

If you do not know what Lambda Function is, then check out my Python Lambda Function Tutorial article on this blog. We can use Lambda function inside the Python filter() built-in function to find all the numbers divisible by 2 in the list. In Python, anonymous function means that a function is without a name. See the below example of filter method with an anonymous function.

If we use the Lambda function, then the size of the code compare to the above code is decreased to 3 lines. See the below code.

# app.py

integers = [21, 19, 18, 46, 6, 29]
even = list(filter(lambda x: x % 2 ==  0, integers))
print(even)

Now, run the file and see the output.

Lambda and Filter function in Python

 

The filter() method returns the iterator that passed the function check for each element in the iterable. The returned elements are those who passed the test.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.