AppDividend
Latest Code Tutorials

Python Filter Example | Python filter() Function

0

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

Python Filter Example

See the following syntax.

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 setsliststuples, or containers of any iterators.

See the following example of the 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 the list and 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 article on this blog.

We can use Lambda function inside the Python filter() built-in function to find all the numbers divisible by 2 on the list. In Python, anonymous function means that a function is without a name. See the below example of a filter method with an anonymous function.

If we use the Lambda function, then the size of the code compared 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.