Lambda and filter in Python
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
Program 1
#filter function in python
def even_odd(n):
if(n%2==0):
return True
else:
return False
#Calling
mylist=[]
n=int(input("Enter the limit: "))
print("Enter elements in collection: ")
for i in range(0,n+1,1):
x=int(input())
mylist.append(x)
mylist1=list(filter(even_odd,mylist))
print("Even Numbers : ")
print(mylist1)
Program 2
#filter function in python with Labmda
#Calling
mylist=[]
n=int(input("Enter the limit: "))
print("Enter elements in collection: ")
for i in range(0,n,1):
x=int(input())
mylist.append(x)
mylist1=list(filter((lambda x:x%2==0),mylist))
print("Even Numbers : ")
print(mylist1)Program 3
#filter function in python
# def pn(n):
# if(n>=0):
# return True
# else:
# return False
# #Calling
# mylist=[12,-9,44,-23,-46,66,7,-9,92]
# mylist1=list(filter(pn,mylist))
# print(mylist1)
# Example with Lambda
# mylist=[12,-9,44,-23,-46,66,7,-9,92]
# mylist1=list(filter((lambda X:X>=0),mylist))
# print(mylist1)
# Program fo Vowel
# def checkvowel(ch):
# if(ch=='a' or ch=='i' or ch=='o' or ch=='u' or ch=='e' or ch=='A' or ch=='I' or ch=='O' or ch=='U' or ch=='E'):
# return True
# else:
# return False
# #Calling
# mylist=['a','T','I','i','e','p','u','r','o','y']
# mylist1=list(filter(checkvowel,mylist))
# print(mylist1)
# Program using Lambda Expression
mylist=['a','T','I','i','e','p','u','r','o','y']
mylist1=list(filter((lambda ch:ch=='a' or ch=='i' or ch=='o' or ch=='u' or ch=='e' or ch=='A' or ch=='I' or ch=='O' or ch=='U' or ch=='E'),mylist))
print(mylist1)
Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

