Updated July 5, 2023
Introduction to Filter in Python
Functional programming facilitates the programmer to write simpler and shorter code. Python also supports the functional programming paradigm. Map, filter, and reduce are built-in functions that simplify programmer life. These three functions allow us to apply our user-defined functions to several iterables like lists, sets, tuples, etc. Python filer() function is used to get filtered items from an iterable like lists, tuples, or sets using a function and returns a sequence of those elements of iterable for which the function returns true.
Syntax:
Python filter() function takes two mandatory arguments. The first is a function, and the second is a valid Python iterable ( list, tuple, sets, etc. )
filter(function/None, iterable)
If the first argument in the filter() function is a function <fun>, then this will be applied to the iterable individual element and returns a sequence of those elements of iterable for which function <fun> returns true.
If the first argument in the filter() function is None; then this will return only those elements from the iterable that is true.
Examples and Usage of Filter () Function in Python
Let’s see some examples of filter() function to have a better understanding of its functionality:
Example #1 – Check eligibility to vote
a. Using the traditional approach
Code:`
valid_voters = [] # defining function to test if entered age is above 18 or not
def eligible_vote(i):
for age in i:
if age >= 18 :
valid_voters.append(age)
# Calling function
eligible_vote((12, 21, 18, 23, 9, 55, 82, 69, 14, 32, 10, 55))
# Printing results
print("these are the eligible voters")
for voter in valid_voters:
print("person with age",voter,"is a valid one")
Output:
b. Using filter() method
Code:
# Function to test a person age > 18 or not --> first argument for filter()
def eligibility(age):
if age >= 18:
return True
else:
return False
# List of all voters --> second argument for filter()
all_voters = [12, 21, 18, 23, 9, 55, 82, 69, 14, 32, 10, 55]
eligible_voters =filter(eligibility , all_voters)
print("these are the eligible voters")
for voter in eligible_voters:
print("age",voter,"is a valid one")
Output:
We can use lambda functions instead of the user-defined function eligibility() in the above code. A lambda function is an anonymous function that doesn’t have any name.
The above code can be modified as follows:
# List of all voters --> second argument for filter()
all_voters = [12, 21, 18, 23, 9, 55, 82, 69, 14, 32, 10, 55]
eligible_voters =filter(lambda age : age >=18 , all_voters)
print("these are the eligible voters")
for voter in eligible_voters:
print("age",voter,"is a valid one")
Output:
The lambda function not only reduces code length; it also enhances readability.
Example #2 – Filter vowels from the input list of alphabets
Code:
count_vowel = 0 # to track no. of vowels
count_consonant = 0 # no. of consonants
alphabets = ['a', 'b', 'U', 'd', 'e', 'i', 'j', 'o', 'x', 'A', 'Z', 't'] # Function to filter out vowels
def filterVowels(alpha):
vowels = ['a', 'e', 'i', 'o', 'u']
if(alpha.lower() in vowels):
return True
else:
return False
filter_vowel = filter(filterVowels, alphabets)
print('The filtered vowels are:')
for vowel in filter_vowel:
count_vowel += 1
print(vowel)
print("total number of alphabets in the list :",len(alphabets))
print("total number of vowels in the list :",count_vowel)
print("total number of consonants in the list :",len(alphabets) - count_vowel)
Explanation:
- Global variables count_vowel and count_consonant are declared to count numbers of vowels and consonants, respectively.
- Define an input list of characters.
- Define a function filterVowels that will return the vowel from the input list.
- Filter () function is called with the first argument as filtervowels() function and input list “alphabets” as the second argument.
- Filter () returns a sequence that contains only vowels( both upper and lower letters )Filtered out from the input list.
- The for loop displays the items from the output sequence, as shown in the following output.
Output:
Example #3 – Filter numbers divisible by 6
Code:
# function to check divisibility by 6
def div_six(x):
if x % 6 == 0:
return True
else :
return False
num_list = [10, 120, 30, 50, 90, 180, 72, 24, 88, 112]
result1 = filter(div_six, num_list)
print("numbers divisbile by 6:")
for num in result1:
print(num)
# using lambda function
result2 = filter(lambda x : x % 6 == 0, num_list)
print("using lambda : numbers divible by 6 :")
for num in result2:
print(num)
Output:
Note: In all the above examples filter() function uses a function/ lambda function as its first argument. It doesn’t need to have a function. We can also specify None instead of a function as its first argument. When the filter function takes None as its parameter, the function defaults to the Identity function, and each element in the given input iterable is checked if it’s true or not. And it will return only true values.
Example #4 – Use of filter() without the filter function
Code:
# a random list
input_list = [(), 100, 7, 'a', 0, False, True, {}, '0', []]
filtered_list = filter(None, input_list)
print('The filtered elements are:')
for item in filtered_list:
print(item)
The “filter()” program ignores False values like empty tuples, empty lists, and False and returns only True values, as shown in the output below.
Output:
Conclusion
Filter () helps select and operate on individual elements of an iterable very efficiently. People typically use it to remove elements in lambda functions. However, it can take none as well as its first argument. It’s up to the user to make the correct use of it.
Recommended Articles
We hope that this EDUCBA information on “Filter in Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information.