Suppose I have a function with side effects (in the example, the side effect is that something is printed). Is there any version of the any() or any construction of the the list iterable which would NOT trigger side effects after finding a True result?
Example, suppose this function:
def a(x):
print("A function got: " + str(x))
return x == 2
One might hope that this call would do the trick. Of course, it does not:
any([
a(i) for i in range(5)
])
Which prints:
A function got: 0
A function got: 1
A function got: 2
A function got: 3
A function got: 4
But I would like it to print this instead:
A function got: 0
A function got: 1
A function got: 2
Why? Range is an iterable, the list comprehension is producing an iterable, I would sort of expect Python to chain those together and stop executing the whole thing as soon as the any() function stops consuming, which it should do once it reaches the first True.
What am I misunderstanding? What version of this would behave in this way, if any?