41

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

1
  • Oh, that would do :)
    – Andrius
    Commented Jul 1, 2015 at 6:54

5 Answers 5

63

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.

3
  • 2
    Also works for namedtuple (since it's a subclass, of course) =)
    – jpmc26
    Commented Sep 22, 2016 at 23:13
  • @TimPietzcke I think it also checks for False (Boolean) value, if one of the value in tuple is False all(t1) will return False
    – sau
    Commented Apr 18, 2017 at 14:12
  • @sau: Yes, False is 0. Commented Apr 18, 2017 at 21:18
22

An answer using all has been provided:

not all(t1)

However in a case like t3, this will return True, because one of the values is 0:

t3 = (0.0, 3, 5)

The 'all' built-in keyword checks if all values of a given iterable are values that evaluate to a negative boolean (False). 0, 0.0, '' and None all evaluate to False.

If you only want to test for None (as the title of the question suggests), this works:

any(map(lambda x: x is None, t3))

This returns True if any of the elements of t3 is None, or False if none of them are.

5

If by any chance want to check if there is an empty value in a tuple containing tuples like these:

t1 = (('', ''), ('', ''))
t2 = ((0.0, 0.0), (0.0, 0.0))
t3 = ((None, None), (None, None))

you can use this:

not all(map(lambda x: all(x), t1))

Otherwise if you want to know if there is at least one positive value, then use this:

any(map(lambda x: any(x), t1))
4

For your specific case, you can use all() function , it checks all the values of a list are true or false, please note in python None , empty string and 0 are considered false.

So -

>>> t1 = (1, 2, 'abc')
>>> t2 = ('', 2, 3)
>>> t3 = (0.0, 3, 5)
>>> t4 = (4, 3, None)
>>> all(t1)
True
>>> all(t2)
False
>>> all(t3)
False
>>> all(t4)
False
>>> if '':
...     print("Hello")
...
>>> if 0:
...     print("Hello")
3
None in (None,2,"a")

True

None in (1,2,"a")

False

"" in (1,2,"")

True

"" in (None,2,"a")

False

import numpy

np.nan in (1,2, np.nan)

True

np.nan in (1,2, "a")

False

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.