DEV Community

Cover image for Python filter() function
Chris Bongers
Chris Bongers

Posted on • Originally published at

Python filter() function

I've recently learned that Python has built-in global functions like JavaScript.
Today we'll be looking into the filter() function.

In general, filters are used to filter a sequence set, for instance, a list.

Filter() function in Python

Let's first have a look at the syntax:

result = filter(myFunction, input)
Enter fullscreen mode Exit fullscreen mode

To give more details to this:

  • result: Is the output. This will be a filtered sequence. So basically the original input, but without some items
  • filter: Is the Python built-in function
  • myFunction: This will be a custom function we are going to build
  • input: This is the original sequence we want to filter

We'll make a list with numbers. Let's say we want to return only the numbers higher than 10.

input = [2, 11, 3, 23, 105, 1, 9, 10]

def myFunction(n):
    return n > 10

result = filter(myFunction, input)
# [11, 23, 105]
Enter fullscreen mode Exit fullscreen mode

As you can see, our input array includes different numbers. We create a myFunction that serves as the filter function.
There we say return if the number is bigger than 10 include that number.

Then we call the filter on our input and print out our new list returning in:

[11, 23, 105]
Enter fullscreen mode Exit fullscreen mode

Already superb, but we can even use lambda functions to make it easier!

input = [2, 11, 3, 23, 105, 1, 9, 10]

result = filter(lambda n: n > 10, input)
Enter fullscreen mode Exit fullscreen mode

And this will result in the same result.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Discussion (2)

waylonwalker profile image
Waylon Walker

Keep on crushing these python posts Chris! Next up you should implement the same filter in a list comprehension. I would be interested in which you feel lis more readable as someone coming from javascript.

dailydevtips1 profile image
Chris Bongers Author

Oh interesting one, will give that a tried as a combined one!
Thanks for that topic