Python filter() Method Explained

Mangabo Kolawole - Apr 14 '22 - - Dev Community

Filtering a list in Python is definitely possible using things such as loops, for loops, or even list/set/dictionary comprehension. However, Python provides the filter() method that is a more clean and efficient way to filter an iterable, much more efficient when it's a large dataset.

The filter() method takes two arguments:

  • a function object
  • an iterable or multiple iterable

The function passed to the filter() method will perform some action on each element of the iterable passed as an argument. The filter function will return to all values from the iterable for which the return condition in the function argument is True.

In the following example, we want to return the values from the list that are equal to banana.

Example

>>> fruits = ["lemon", "orange", "banana"]
>>> def check_banana(fruit):
...         return fruit == "banana"
...
>>> new_fruits = filter(check_banana, fruits)
<filter object at 0x7f080634b400>
>>> new_fruits = list(new_fruits)
>>> new_fruits
['banana']
Enter fullscreen mode Exit fullscreen mode

Notice that you have to convert the returned filter object into an iterable so you can work with it easily.

It's also possible to use filter() with lambda functions.

>>> new_fruits = filter(lambda fruit: fruit == "banana", fruits)
>>> new_fruits = list(new_fruits)
>>> new_fruits
['banana']
Enter fullscreen mode Exit fullscreen mode

You can learn more about the method here.

Article posted using bloggu.io. Try it for free.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player