Search code examples
pythonperformancelist-comprehensionany

Speeding up `any` with list comprehension


I am using any with a list comprehension. I would like to break the list comprehension when any returns True. For example,

import time

def f(x):
    time.sleep(2)
    return x

beginTime = time.time()
result = any([f(x) == 0 for x in [0,1,3,5,7]])
endTime = time.time()

print(endTime - beginTime)

The above code prints 10 seconds although it could break the iteration after first True.


Solution

  • Use a generator expression instead of a list comprehension to avoid forming the list first:

    result = any(f(x) == 0 for x in [0,1,3,5,7])
    

    (the square brackets of the list comprehension are gone.)

    Note that any has a short-circuiting behaviour in either case, but what differs is the lack of forming the whole list.