Home »
Python »
Python programs
Check if value is in a List using Lambda Function in Python
Learn how to Check if value is in a List using Lambda Function in Python?
Submitted by IncludeHelp, on March 14, 2022
Given a list and an element, we have to check whether the element is present in the list or not using the Lambda function.
Example:
Input:
list1 = [10, 15, 20, 25, 30]
ele = 15
Output: Yes
Input:
list1 = [10, 15, 20, 25, 30]
ele = 12
Output: No
To check an element in the list, we will use two methods with lambda functions. In the first method – we will use the count() function, The count() method returns the number of elements with the specified value. And, in the second method – we will use in keyword, the 'in' keyword is used to check if a value is present in a sequence (list, range, string etc.).
Method 1: Using lambda and count() function
There is an integer list, define a lambda function that will take the list and will return the count of the given element.
Python code to check if value is in a list using lambda and count() function
# Using lambda and count() function
list1 = [10, 15, 20, 15, 30]
ele = 15
# Lambda function to check an element
# in the list
countFunc = lambda list1 , ele : list1.count(ele)
count = countFunc(list1, ele)
if(count):
print("Yes, total count of", ele, "is",count)
else:
print("No")
Output:
Yes, total count of 15 is 2
Method 2: Using lambda and in keyword
There is an integer list, define a lambda function that takes the list and an element to check and returns True if element presents in the list; False, otherwise using in keyword.
Python code to check if value is in a list using lambda and in keyword
list1 = [10, 15, 20, 15, 30]
ele = 15
# Lambda function to check an element
# in the list
countFunc = lambda list1, ele: True if ele in list1 else False
if(countFunc(list1,ele)):
print("Yes")
else:
print("No")
Output:
Yes
Python Lambda Function Programs »