Python filter() function constructs an iterator from elements of an iterable for which a function returns true. We can understand that filter will test every element of iterators to be true or not.

A Quick Example

marks = [5, 7, 2, 8, 9]
def is_pass_test(x):
  if m < 5:
    return False
  else:
    return True

passes = filter(is_pass_test, marks)
print(list(passes))

/* Result: [7, 8, 9] */
Python Filter Function, quickly filter your data in Python
Quickly filter your data in Python.
(Berlin – Source: Wallpapers Wide)

Definition and Usage

The Python filter() syntax is as follows:

filter(function, iterable)
  • function: The function will be executed for each element of iterable.
  • iterable: The iterable to be filtered.

Python Filter Examples

Example 1: Using lambda function with filter()

We can make above example a lot shorter by using lambda with filter()

marks = [5, 7, 2, 8, 9]

passes = filter(lambda x: x > 5, marks)
print(list(passes))

/* Result: [7, 8, 9] */

You don't know what is lambda, don't worry, read our article to understand it (What's lambda syntax in Python)

Example 2: Passing None function to filter()

datas = [5, False, '', True, 'Filtered', None]

passes = filter(None, datas)
print(list(passes))

/* Result: [5, True, 'Filtered'] */

In this example, we passed None as a function parameter. However it is not a real None value, it means a default function. In this case, a default function equal to lambda x: x

References

As our goal to build a short and understandable tutorial. However, in case you would like to learn deeper, you should read below references:

 

Sharing is caring!

1 thought on “Python Filter Function

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *