Built in function Grammar/Environments

[Python]How to Use filter() Function

This article shows how to use filter() function.

Contents

  • Basic usage of filter( ) function
  • Combination of filter( ) and lambda function
  • Applying filter( ) function to a dictionary
  • Comparison of filter( ) and map( ) functions

sponsored link

Basic usage of filter( ) function

In the beginning, I show basic usage of filter( ) function.

By using filter( ) function, elements that meet conditions can be extracted from the iterable object.

The filter( ) function is built-in function in Python.

So, we can use filter( ) function without "import".

Specify function as the first argument and iterable object (list, tuple, etc.) as the second argument.

How to write

filter( function, iterable )

The filter() function extracts elements from a list for which a function returns True.

Applying filter() function to a list

I show how to apply filter() function to a list.

This is an example code.

Only odd-numbered elements are extracted from a list.

my_list = list(range(10))
print(my_list)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

def is_odd(x):
    return x % 2 == 1

print(filter(is_odd, my_list))
# <filter object at 0x000001A01E164F28>
print(list(filter(is_odd, my_list)))
# [1, 3, 5, 7, 9]

> def is_odd(x):
> return x % 2 == 1

The function is defined that returns True if the remainder divided by 2 is 1.

> print(filter(is_odd, my_list))
> # <filter object at 0x000001A01E164F28>

A filter object is generated.

> print(list(filter(is_odd, my_list)))
> [1, 3, 5, 7, 9]

Since the elements cannot be checked as a filter object, they are converted to list type with the list( ) function.

Combination of filter( ) and lambda function

I show how to use filter( ) function in combination with lambda.

If a function is simple, lambda can be used to write concise code.

This is an example code.

my_list = list(range(10))
print(my_list)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(list(filter(lambda x : x % 2 == 1, my_list)))
# [1, 3, 5, 7, 9]

> print(list(filter(lambda x : x % 2 == 1, my_list)))

The function is defined using lambda.

How to use lambda is explained in this article.

How to Use Lambda Function

Extract elements with a specified number of characters using filter() and len() functions.

I show another example code.

By using len( ) function, elements with a specified number of characters are extracted.

list_fruits = ['Apple', 'Banana', 'Orange', 'Grape', 'Mango', 'Lemon', 'Peach', 'Plum']

print(list(filter(lambda x : len(x) == 5, list_fruits)))
# ['Apple', 'Grape', 'Mango', 'Lemon', 'Peach']

sponsored link

Applying filter( ) function to a dictionary

I show how to apply filter() function to a dictionary.

Applying filter( ) function to dictionary keys

This is an example code.

dict_fruits1 = {'Apple':100, 'Banana':200, 'Grape':500, 'Orange':100}

keys = set(['Banana', 'Orange'])
dict_fruits2 = dict(filter(lambda fruit : fruit[0] in keys, dict_fruits1.items()))
print(dict_fruits2)
# {'Banana': 200, 'Orange': 100}

> keys = set(['Banana', 'Orange'])

Describe the keys to be extracted.
set( ) function is used to convert a list to set type.

> dict_fruits2 = dict(filter(lambda fruit : fruit[0] in keys, dict_fruits1.items()))

It is in the form of "dict( filter( function, iterable ) )"
Elements extracted by filter( ) function are converted to dictionary type by dict( ) function.

As "iterable", "dict_fruits1.items()" is specified.

Applying items( ) method to a dictionary allows you to get all keys and elements contained in a dictionary.

As "function", "lambda fruit : fruit[0] in keys" is specified.

The function returns True if "fruit[0]" is contained in "keys".

Applying filter( ) function to dictionary values

This is an example code.

dict_fruits1 = {'Apple':100, 'Banana':200, 'Grape':500, 'Orange':100}

dict_fruits2 = dict(filter(lambda fruit : fruit[1] >= 200, dict_fruits1.items()))
print(dict_fruits2)
# {'Banana': 200, 'Grape': 500}

Comparison of filter( ) and map( ) functions

As a supplement, I show difference between filter( ) and map( ) function.

Like filter( ) function, map( ) also takes "function" and "iterable" as arguments.

How to write

map( function, iterable )

By using map(), function can be applied to all elements of the iterable object( list, tuple, etc.).

This is an example code.

The same user-defined function is specified as argument for filter( ) and map( ) function.

dict_fruits1 = {'Apple':100, 'Banana':200, 'Grape':500, 'Orange':100}

def my_func(x) :
    return x[1] >= 200

print(list(map(my_func, dict_fruits1.items())))
# [False, True, True, False]

print(list(filter(my_func, dict_fruits1.items())))
# [('Banana', 200), ('Grape', 500)]

How to use map( ) function is explained in this article.

How to use map( ) function

sponsored link

-Built in function, Grammar/Environments
-,

This article shows how to use filter() function.