Python filter() Function: Use, Syntax, and Examples

Python filter() function: In this tutorial, we will learn about the filter() function in Python with its use, syntax, parameters, returns type, and examples. By IncludeHelp Last updated : June 24, 2023

Python filter() Function

The filter() function is a library function in Python, it 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

The following is the syntax of filter() function:

filter(function, sequence)

Parameter(s):

The following are the parameter(s):

  • 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

The filter() function 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]


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.