Skip to content

[Python] How to use filter() function

Last Updated on 2020-11-12 by Clay

Python is the most popular programming language!

Introduction

Today when I was answering a question asked by a friend, I see a filter() function in my friend's code, and my friend just asked me what was wrong with this paragraph.

This is a awkward question. I have been learning Python for two years, but I never used this function in my program.

No one is perfect, so I checked the usage fo this filter() function and record it in this article.


How to use filter() function

In fact, it is very easy. We just need to input two parameters:

filter(FUNCTION, ITERABLE_OBJECT)

And the filter() function will return the elements whose result is True.

I know this is very difficult to understand, so we look at a sample code:

# Inputs
inputs = [
    'a',
    'bb',
    'ccc',
    'dddd',
    'eeeee',
]


# Function
def bigger_than_three(string):
    return True if len(string) > 3 else False


# Filter
result = filter(bigger_than_three, inputs)
print(result)
print(list(result))


Output:

<filter object at 0x7f0f92d34860>
['dddd', 'eeeee']

First I defined a input parameter inputs that is a List and there are many different length string in it.

And then I define a bigger_than_three() function, if the length of input string is bigger than 3, the function will return True; If it is not, the function will return False.

And we input the List and the bigger_than_three() function to the filter() function. As you can see, If the string of List bigger than 3, the string will be returned.

This is the function of the filter() function, filtering out the elements that we don't need.


References


Read More

Tags:

Leave a Reply