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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With