Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to check if a tuple has any empty/None values in Python?

What is the best/most efficient way to check if all tuple values? Do I need to iterate over all tuple items and check or is there some even better way?

For example:

t1 = (1, 2, 'abc') t2 = ('', 2, 3) t3 = (0.0, 3, 5) t4 = (4, 3, None) 

Checking these tuples, every tuple except t1, should return True, meaning there is so called empty value.

P.S. there is this question: Test if tuple contains only None values with Python, but is it only about None values

like image 433
Andrius Avatar asked Jul 01 '15 06:07

Andrius


People also ask

How do you check the tuple is empty or not?

The preferred way to check if any list, dictionary, set, string or tuple is empty in Python is to simply use an if statement to check it. def is_empty(any_structure): if any_structure: print('Structure is not empty.

How do you check if a tuple contains a value?

Method 1: By using a loop: We will iterate through each items of the tuple one by one and compare it with the given value. If any value in the tuple is equal to the given value, it will return True. Else, it will return False.

Is Empty tuple false?

In python, an empty tuple always evaluates to false. So when we passed an empty tuple to the if condition it'll be evaluated to false. But the not operator reverses the false value to the true value.

Can a tuple be empty in Python?

There are two ways to initialize an empty tuple. You can initialize an empty tuple by having () with no values in them. You can also initialize an empty tuple by using the tuple function. A tuple with values can be initialized by making a sequence of values separated by commas.


1 Answers

It's very easy:

not all(t1) 

returns False only if all values in t1 are non-empty/nonzero and not None. all short-circuits, so it only has to check the elements up to the first empty one, which makes it very fast.

like image 199
Tim Pietzcker Avatar answered Sep 24 '22 16:09

Tim Pietzcker