Andrius
Andrius

Reputation: 21168

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

Upvotes: 41

Views: 87130

Answers (5)

Pablo Vilas
Pablo Vilas

Reputation: 586

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

Upvotes: 3

tsveti_iko
tsveti_iko

Reputation: 8022

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))

Upvotes: 5

Grismar
Grismar

Reputation: 31354

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.

Upvotes: 22

Anand S Kumar
Anand S Kumar

Reputation: 90979

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")

Upvotes: 4

Tim Pietzcker
Tim Pietzcker

Reputation: 336378

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.

Upvotes: 63

Related Questions