Python Function

filter() in Python

filter() in Python

Introduction

The filter() method in python filters the given collection or sequence with the help of a function which tests each element in the sequence holds true or not.

Syntax

Below is the syntax used for defining the filter function:

filter(function, sequence)

Parameters

Parameters used by Python filter() function is enlisted below:

  • function: it is the function that tests if each element of a sequence true or not.
  • sequence: it is the sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators.

Return Value

This function returns an filtered iterator that can be iterated upon.

Examples

Example 1: Using filter() function with a normal function

Here, we are using filter() function by passing a normal function to filter values from the list.

def myFun(a):

    lst = ['a', 'b', 'c', 'd', 'e']

    if(a in lst):

        return True

    else:

        return False

        

list1 = ['b', 'o', 'a', 'r', 'd', 'i', 'n', 'f', 'i', 'n', 'i', 't', 'y', ]

filtered = filter(myFun, list1)

  

print('The filtered list elements are:')

for s in filtered:

    print(s)

Output:

The filtered list elements are:

b

a

d

write your code here: Coding Playground

Example 2: Using filter() function with a lambda function

Here, we are using filter() function by passing a lambda function to filter values from the list.

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


result = filter(lambda x: x % 3 != 0, lst)

print(list(result))


result = filter(lambda x: x % 3 == 0, lst)

print(list(result))

Output:

[1, 2, 5, 7, 8, 8, 8, 5, 4, 1]

[3, 6, 9]

write your code here: Coding Playground

Example 3: Using filter() function for filtering vowels and consonants

Here, we are using filter() function for filtering vowels and consonants

def myFun(a):

    lst = ['a', 'e', 'i', 'o', 'u']

    if(a in lst):

        return True

    else:

        return False

        

def myFun1(a):

    lst = ['a', 'e', 'i', 'o', 'u']

    if(a not in lst):

        return True

    else:

        return False

        

list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 

        'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

filtered1 = filter(myFun, list1)

filtered2 = filter(myFun1, list1)

  

print('All vowels are:')

for s in filtered1:

    print(s)


print('All consonants are:')

for s in filtered2:

    print(s)

Output:

All vowels are:

a

e

i

o

u

All consonants are:

b

c

d

f

g

h

j

k

l

m

n

p

q

r

s

t

v

w

x

y

z

write your code here: Coding Playground