filter pythn 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: python - filter function

# Filter function
def with_s(student):
    return student.startswith('s')

students = ['sarah', 'mary', 'sergio', 'lucy']   # define a list
s_filter = filter(with_s, students)              # filter() returns true or false
print(next(s_filter))                            # filter() returns a generator
print(list(s_filter))                            # give all elements of the generator