2

If you have:

if any(word in sentence for sentence in sentences):

and sentences is a long list of say, 10,000 sentence-length strings, will any() iterate through the entire list to determine if any are true, or will it stop looking once a true value is found, since the any() value is already determined to be true?

If it's truly iterating through the entire list regardless, then of course if would be faster to use a for loop and break once found, as opposed to using any(), that's why I'm asking.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101

1 Answers1

3

Yes, it does short-circuit like that. From the documentation:

Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

One easy way to confirm is with a large or infinite iterable:

>>> any(True for i in range(1_000_000_000_000))
True

(instant)

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Thanks! And now that I understand this is called "short-circuiting", its easy to find more information on the subject. Did not know there was a name for this. – WisconsinBadger414 Jun 16 '20 at 00:52