-2

Consider the following python instruction

any([condition(element) for element in some_list])

Is it optimised to stop once condition(element) is True, or any is applied after the whole list of boolean values is built?

If case the the whole list is created, is there a way to avoid it, apart from coding an explicit loop?


Let me clarify the question, since someone misunderstood it.

Scenario 1. condition(element) is evaluated for each element of some_list and list of boolean values (containing True or False for corresponding element of some_list) is created. Only after that any is applied to the created list of booleans.

Scenario 2. Instead of evaluating condition(element) for each element, the lookup stops immediately after condition(element) holds for certain element of some_list

Is Python optimised to follow Scenario 2 rather than Scenario 1?

cyanide
  • 3,885
  • 3
  • 25
  • 33
  • 5
    `any()` will stop on the first truthy value - but you have explicitly constructed a list here, that will have to be fully evaluated before it can be passed to `any()`. Just get rid of those square brackets, which will make it a *generator expression* rather than a *list comprehension* - the generator will only be iterated until the first truthy value. – jasonharper Apr 02 '23 at 23:23
  • jasonharper. Just removing square brackets! That's the answer I was looking for! Such a shame that I can't mark it as the answer. The documentation says that, 'any' applies only to iterable, while I believed that without square brackets it won't be considered as iterable. – cyanide Apr 03 '23 at 00:13

1 Answers1

2

According to the doc https://docs.python.org/3/library/functions.html#any any is like this:

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

So it is already optimized.

TheEngineerProgrammer
  • 1,282
  • 1
  • 4
  • 9
  • The same you can find in the doc: https://docs.python.org/3/library/functions.html – TheEngineerProgrammer Apr 02 '23 at 23:30
  • The specific link https://docs.python.org/3/library/functions.html#any – Chris Doyle Apr 02 '23 at 23:31
  • ??? wasn't que question about if any() will stop on the first truthy value??? – TheEngineerProgrammer Apr 02 '23 at 23:34
  • This documentation doesn't look clear to me. Of course, if the whole list of boolean values is formed, the lookup stops once True is found. However creating the whole list is actually unnecessary, so the question was whether Python is smart enough to figure that out. – cyanide Apr 02 '23 at 23:41
  • 1
    So you what to see the original source. Check out the github: https://github.com/python/cpython/blob/3.10/Python/bltinmodule.c the function builtin_any, is written in C which I don't understant much. – TheEngineerProgrammer Apr 02 '23 at 23:51
  • @cyanide python simply cannot make that optimization, because there is no guarantee that you are only using pure functions. – juanpa.arrivillaga Apr 03 '23 at 04:26