filter array python code example

Example 1: what are filters in python

In simple words, the filter() method filters the given iterable 
with the help of a function that tests
each element in the iterable to be true or not.

Filter Methods is simply a like comprarator class of c++ STL


Code Explanation: 
  # A simple tutorial to show the filter 
# methods in python

grades = ['A','B','C','F']

def remove_fails(grades):
    return grades!='F'

print(list(filter(remove_fails,grades)))

Example 2: filter array python

A = [6, 7, 8, 9, 10, 11, 12]
subset_of_A = set([6, 9, 12]) # the subset of A

result = [a for a in A if a not in subset_of_A]

Example 3: filter function in python

nums1 = [2,3,5,6,76,4,3,2]

def bada(num):
    return num>4 # bada(2) o/p: False, so wont return.. else anything above > value returns true hence filter function shows result  

filters = list(filter(bada, nums1))
print(filters)
 
(or) 
 
bads = list(filter(lambda x: x>4, nums1))
print(bads)