0
Q:

filter array python

# 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
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)
1
# 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
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]
0

New to Communities?

Join the community