When it is required to check if a tuple has any 'None' value or not, the 'any' method, the 'map' method and the lambda function can be used.
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.
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 'any' method checks to see the iterable if at least one True value exist. If yes, it returns True, else False.
Below is a demonstration of the same −
Example
my_tuple = (31, 45, 12, 56, 78, None, None) print("The tuple is : ") print(my_tuple) my_result = any(map(lambda elem: elem is None, my_tuple)) print("Does the tuple contain any None value ? " ) print(my_result)
Output
The tuple is : (31, 45, 12, 56, 78, None, None) Does the tuple contain any None value ? True
Explanation
- A tuple is defined and is displayed on the console.
- The lambda function is applied on each element in the tuple using 'map' method.
- The any function is called on this result and it is assigned to a variable.
- This variable is displayed on the console.