Python filter() Method
In this tutorial we will learn about python filter method and its uses.
Python filter() Method
What is Python filter() Method?
The filter() method returns an iterator where the items are filtered through a method to test if the item is true or not.
The syntax of filter() method is:
1
2
filter(method, iterable)
Python filter() Method Parameters
filter() method takes two parameters:
- method - it will take a method that tests if elements of an iterable return true or false.
- iterable - iterable which will be filtered, can be sets, lists, tuples, or containers of any iterators
Let us see some examples of filter() method.
Example 1: How filter() method works for the iterable list?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# list of letters
letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o']
# function that filters vowels
def filter_vowels(letter):
vowels = ['a', 'e', 'i', 'o', 'u']
if(letter in vowels):
return True
else:
return False
filtered_vowels = filter(filter_vowels, letters)
print('The filtered vowels are:')
for vowel in filtered_vowels:
print(vowel)
The output will be as follow:
1
2
3
4
5
6
The filtered vowels are:
a
e
i
o
Rules of filter() method
filter() method can take only an iterator as an input which can be passed in method to check for each element in the iterable.
This post is licensed under CC BY 4.0 by the author.