Q:

Python program to check for None tuple

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Checking For None Values in Python

In this program, we are given a tuple consisting of some values. And we will be creating a Python program that will check whether the given Tuple is a None tuple or not.

None Tuple is a tuple whose all values are none.

Example:
(None, None, None)

To check for None Tuple we need to traverse the tuple and check if each value is a None value or not. If all values are none, return true otherwise false.

This can be performed in Python using multiple method combinations. Let's see some of them here.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to check for none tuple is to check if all elements are None by using the all() method with a generator expression.

# Python program to check for 
# none tuple 

# Initializing and printing tuple
myTuple = (None, None, None, None, None)
print("The elements of tuple : " + str(myTuple))

# Checking for None tuple
isNone = all(val is None for val in myTuple)
print("Is the given tuple a none tuple? " + str(isNone))

Output:

The elements of tuple : (None, None, None, None, None)
Is the given tuple a none tuple? True

Method 2:

One more method to check if the tuple is a none tuple or not is by comparing the number of none values in the tuple which is the length of the tuple. If both are the same then the tuple is none tuple otherwise not.

The length of the tuple is calculated using len() method and the count of none elements is found using the count() method.

# Python program to check for 
# none tuple 

# Initializing and printing 
# tuple
myTuple = (None, None, None, None, None)
print("The elements of tuple : " + str(myTuple))

# Checking for None tuple
isNone = len(myTuple) == myTuple.count(None)
print("Is the given tuple a none tuple? " + str(isNone))

Output:

The elements of tuple : (None, None, None, None, None)
Is the given tuple a none tuple? True

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to convert tuple to adjacent pair d... >>
<< Python program to perform subtraction of elements ...