If it is required to check if a tuple contains a specific value 'K', it can be done using the 'any' method, the 'map' method and the lambda function.
Anonymous function is a function which is defined without a name. In general, functions in Python are defined using 'def' keyword, but anonymous function is defined with the help of 'lambda' keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it.
The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.
The 'any' method checks if any of the elements in the iterable are True, and if that's the case, returns Ture, else returns False.
Below is a demonstration of the same −
Example
my_tuple = ( 67, 45, 34, 56, 99, 123, 10, 56) print ("The tuple is : " ) print(my_tuple) K = 67 print("The value of 'K' has been initialized") my_result = any(map(lambda elem: elem is K, my_tuple)) print("Does tuple contain the K value ?" ) print(my_result)
Output
The tuple is : (67, 45, 34, 56, 99, 123, 10, 56) The value of 'K' has been initialized Does tuple contain the K value ? True
Explanation
- A tuple is defined, and is displayed on the console.
- The value of 'K' is also initialized.
- The list comprehension is used to iterate through the tuple using the lambda function.
- This operation is mapped to all elements in the tuple.
- This result is checked for, using the 'any' method.
- This operation is assigned a variable.
- This variable is the output that is displayed on the console.