learner
0
Q:

python filter

number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)

# Output: [-5, -4, -3, -2, -1]
18
# 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]
6
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)))
4
# 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)  
2
# 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
-1

New to Communities?

Join the community