Check if all elements of nested iterability match False

I have the following code (list of tuples):

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

How do 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 
+4
source share
2 answers

Use the nested any() calls:

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

any() returns False only if all the elements in iterable passed to it are False . not any() , thus 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 
+9
source

You can use any with itertools.chain , it is faster than a nested any , because it does not require the python for-loop:

Several alternatives:

 not any (chain.from_iterable(x)) not any (chain(*x)) not any(map(any,x)) not any(imap(any,x)) #itertools.imap 

Terms of comparison:

 >>> from itertools import chain,imap >>> x = [(None, None, None), (None, None, None), (None, None, None)] >>> %timeit not any (chain.from_iterable(x)) #winner 100000 loops, best of 3: 1.08 us per loop >>> %timeit not any (chain(*x)) 1000000 loops, best of 3: 1.29 us per loop >>> %timeit not any(any(inner) for inner in x) 100000 loops, best of 3: 1.76 us per loop >>> %timeit not any(map(any,x)) 100000 loops, best of 3: 1.5 us per loop >>> %timeit not any(imap(any,x)) 100000 loops, best of 3: 1.37 us per loop >>> x = [(None, None, None), (None, None, None), (None, None, None)]*1000 >>> %timeit not any (chain.from_iterable(x)) #winner 1000 loops, best of 3: 462 us per loop >>> %timeit not any (chain(*x)) 1000 loops, best of 3: 537 us per loop >>> %timeit not any(any(inner) for inner in x) 1000 loops, best of 3: 1.26 ms per loop >>> %timeit not any(map(any,x)) 1000 loops, best of 3: 672 us per loop >>> %timeit not any(imap(any,x)) 1000 loops, best of 3: 765 us per loop >>> x = [(None, None, None), (None, None, None), (None, None, None)]*10**5 >>> %timeit not any (chain.from_iterable(x)) #winner 10 loops, best of 3: 50.1 ms per loop >>> %timeit not any (chain(*x)) 10 loops, best of 3: 70.3 ms per loop >>> %timeit not any(any(inner) for inner in x) 10 loops, best of 3: 127 ms per loop >>> %timeit not any(map(any,x)) 10 loops, best of 3: 76.2 ms per loop >>> %timeit not any(imap(any,x)) 1 loops, best of 3: 64.9 ms per loop 
+3
source

Source: https://habr.com/ru/post/1490546/


All Articles