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 some of the built-in functions which make programmer life easy. These three functions allow us to apply our user-defined functions to a number of 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 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 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
Let’s see some examples of filter() function to have a better understanding of its functionality:
Example #1 – Program to 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:
Instead of user-defined function eligibility() in the above code, we can use lambda functions. Lambda function is an anonymous function means it doesn’t have any name.
The above code can be modified as:
# 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:
Lambda function not only reduces code length; it also enhance readability.
Example #2 – Program to filter out 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 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.
- for loop is used to print the items from the output sequence as shown in the below output.
Output:
Example #3 – Program to filter out numbers that are 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 specify None as well 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 – Program to demonstrate usage 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)
In this program, False values like empty tuple, empty list, False are ignored by the filter(), and only True values are returned as shown in the below output.
Output:
Conclusion
filter() helps in selecting and operating on individual elements of an iterable very efficiently. It is normally used with lambda functions to filter out elements. 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
This is a guide to Filter in Python. Here we discuss the introduction, different examples, and usage of filter() Function in python. You may also have a look at the following articles to learn more –
40 Online Courses | 13 Hands-on Projects | 215+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses