python filter
# 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, 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]
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)))
# Python Program to find numbers divisible
# by thirteen from a list using anonymous
# function
# Take a list of numbers.
my_list = [12, 65, 54, 39, 102, 339, 221, 50, 70, ]
# use anonymous function to filter and comparing
# if divisible or not
result = list(filter(lambda x: (x % 13 == 0), my_list))
# printing the result
print(result)
# 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