filter() in python

The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.

syntax:

filter(function, sequence)

Parameters:

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

Returns:

returns an iterator that is already filtered.

Program 1 : Using normal function

# list of alphabets
letters = ['a', 'b', 'd', 'e', 'p', 'j', 'i','s', 'o', 'r', 'u']
# function that filters non-vowels
def filter_non_vowels(letters):
   vowels = ['a', 'e', 'i', 'o', 'u']
   if(letters in vowels):
       return False
   else:
       return True
filter_non_vowels = filter(filter_non_vowels, letters)
print('The filtered non-vowels are:')
for non_vowel in filter_non_vowels:
   print(non_vowel)

Output :

The filtered non-vowels are:
b
d
p
j
s
r

Application:

  • It is normally used with Lambda functions to separate list, tuple, or sets.

Program 2:Using lambda Function

# a list contains both even and odd numbers.  

seq = [0, 1, 2, 3, 5, 8, 13]
# result contains odd numbers of the list
result = filter(lambda x: x % 2 != 0, seq)
print(list(result))
# result contains even numbers of the list
result = filter(lambda x: x % 2 == 0, seq)
print(list(result))

Output:

[1, 3, 5, 13]
[0, 2, 8]

Β 

Β