Python | Check for None Tuple

Sometimes, while working with Python records, we can have a problem in which we need to filter out all the tuples which contains just None values. This can have possible application in Data Science domain. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using all() + generator expression
The combination of above functionalities can be used to perform this particular task. In this we feed the logic of finding None using generator expression and checking for each element is handled by all().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Check for None Tuple
# using all() + generator expression
  
# initialize tuple
test_tup = (None, None, None, None, None)
  
# printing original tuple
print("The original tuple : " + str(test_tup))
  
# Check for None Tuple
# using all() + generator expression
res = all(ele is None for ele in test_tup)
  
# printing result
print("Does tuple contain all None elements ? : " + str(res))

chevron_right


Output :



The original tuple : (None, None, None, None, None)
Does tuple contain all None elements ? : True

 

Method #2 : Using len() + count()
The combination of above functions can be used to perform this task. In this, we just count the occurrences of None and equate to list length to check if all elements are None.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Check for None Tuple
# using len() + count()
  
# initialize tuple
test_tup = (None, None, None, None, None)
  
# printing original tuple
print("The original tuple : " + str(test_tup))
  
# Check for None Tuple
# using len() + count()
res = len(test_tup) == test_tup.count(None)
  
# printing result
print("Does tuple contain all None elements ? : " + str(res))

chevron_right


Output :

The original tuple : (None, None, None, None, None)
Does tuple contain all None elements ? : True



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.