ADVERTISEMENT
ADVERTISEMENT

Python filter() Function with Examples

Learn about the filter() function, its usages, syntax, and examples.
Submitted by IncludeHelp, on March 07, 2022

In Python programming language, the filter() function is a built-in function that is used to filter the given sequence (sets, lists, tuples, etc.) with the help of a function that checks each element in the given sequence to be true or not.

Syntax of filter() function

filter(function, sequence)

Here,

  • function : A function that is used to check each element of the sequence whether true or not.
  • sequence : A sequence like sets, lists, tuples, etc., needs to be filtered.

Return value of filter() function

It returns an iterator of filtered elements.

Python filter() Function (Example 1)

# Python program to demonstrate the 
# example of filter() function 

# Function to filter vowels from the sequence
def filterVowels(s):
    vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
    if (s in vowels):
        return True
    else:
        return False
  
  
# Defining a sequence
seq = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
  
# Filtering the vowels using filter() function
result = filter(filterVowels, seq)
  
print('The result is:')
for s in result:
    print(s)

Output:

The result is:
e
o
o

Python filter() Function (Example 2)

The filter() function is normally used with the lambda functions to filter the elements of a sequence like  sets, lists, tuples, or containers of any iterators.

# Python program to demonstrate the 
# example of filter() function 

# list of integers
fibo = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

print("Original List  :",fibo)

# filter even numbers using 
# filter() and lambda
even =  list(filter(lambda n:n%2==0,fibo))

print("Even List     :",even)

Output:

Original List  : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Even List     : [0, 2, 8, 34]
ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.