Check for None Tuple in Python

PythonServer Side ProgrammingProgramming

When it is required to check for 'None' value in a tuple, the 'all' method and the generator expression can be used.

The 'all' method checks to see if all the values inside an iterable are True values. If yes, it returns True, else returns False.

Below is a demonstration of the same −

Example

Live Demo

my_tuple_1 = (None, None, None, None, None, None, None )

print ("The tuple is : " )
print(my_tuple_1)

my_result = all(elem is None for elem in my_tuple_1)

print("Does the tuple contain only None values ? ")
print(my_result)

Output

The tuple is :
(None, None, None, None, None, None, None)
Does the tuple contain only None values ?
True

Explanation

  • A tuple is defined and is displayed on the console.
  • It is iterated over using list comprehension and the 'all' method is used to check the elements in the tuple.
  • This result is assigned to a value.
  • It is displayed as output on the console.
raja
Published on 12-Mar-2021 10:03:56
Advertisements