Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all elements in nested iterables evaluate to False

Tags:

python

I have the following code (a list of tuples):

x = [(None, None, None), (None, None, None), (None, None, None)]

How would I know that this essentially evaluates to False?

In other words, how could I do something like:

if not x: # x should evaluate to False
    # do something
like image 868
David542 Avatar asked Dec 15 '22 08:12

David542


1 Answers

Use nested any() calls:

if not any(any(inner) for inner in x):

any() returns False only if all of the elements in the iterable passed to it are False. not any() thus is True only if all elements are false:

>>> x = [(None, None, None), (None, None, None), (None, None, None)]
>>> not any(any(inner) for inner in x)
True
>>> x = [(None, None, None), (None, None, None), (None, None, 1)]
>>> not any(any(inner) for inner in x)
False
like image 113
Martijn Pieters Avatar answered Feb 01 '23 11:02

Martijn Pieters