Python Filter Function

Table Of Contents:

  1. What Is A Filter Function?
  2. Syntax Of Filter Function.
  3. Examples Of Filter Function.

(1) What Is A Filter Function?

  • Python filter( ) method is an inbuilt method, which is used to filter out the required values from an iterable like(a list, tuple, set, or dictionary).
  • The filter( ) method will return an iterator that you can easily convert iterators to sequences like lists, tuples, strings etc.

(2) Syntax Of Filter Function.

filter(function, iterable)

Filter Parameters:

  • function: A Function to be run for each item in the iterable
  • iterable: The iterable to be filtered.

Filter Return Type:

  • The filter( ) function returns an iterator like (list, tuple, set, dictionary.)

(3) Examples Of Filter Function.

Example-1:Filtering The Even Numbers

numbers = [1,2,3,4,5,6,7,8,9,10]

def even(n):
    if n % 2 == 0:
        return n
    
filtering = filter(func,numbers)

even = list(filtering)

print(even)
Output:
[2, 4, 6, 8, 10]

Example-2: Filtering Numbers Greater Than 5.

numbers = [2,4,5,6,9,5,4,10,15,99]

def greater(n):
    if n > 5:
        return n

filtered = filter(greater,numbers)

numbers = list(filtered)

print(numbers)
Output:
[6, 9, 10, 15, 99]

Example-3: Filtering Numbers From Mixed List.

numbers = [1,'a',2,'e',3,'i',4,'o',5]

def number(n):
    if type(n) == int:
        return n

filtered = filter(number,numbers)

numbers = list(filtered)

print(numbers)
Output:
[1, 2, 3, 4, 5]

Leave a Reply

Your email address will not be published. Required fields are marked *