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

5

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

Sandler answered 1/7, 2015 at 6:49 Comment(1)
Oh, that would do :)Sandler
F
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.

Freeze answered 1/7, 2015 at 6:52 Comment(3)
Also works for namedtuple (since it's a subclass, of course) =)Micron
@TimPietzcke I think it also checks for False (Boolean) value, if one of the value in tuple is False all(t1) will return FalseIdealize
@sau: Yes, False is 0.Freeze
H
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.

Hash answered 15/11, 2017 at 3:21 Comment(0)
L
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))
Livvy answered 18/6, 2018 at 15:7 Comment(0)
P
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")
Photoelectric answered 1/7, 2015 at 6:53 Comment(0)
S
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

Scriber answered 7/5, 2021 at 15:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.