why OR returns True if the first element is True, but ANY still checks all element even if the first element is True

Viewed 55
>>> 1 or 1/0
1
>>> any([1, 1/0])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

I thought any() could also return True as long as it finds the first True element in the iterable, but why it still checks all elements? Won't it lead to a worse runtime?

1 Answers

You're correct, any does short-circuit (only evaluates as much as needed) but as @alfasin said, you're creating the 1/0 error when you try and insert it into a list. To show the delayed evaluation, you'd have to do something like what I put in the comments or

def itr():
    yield 1
    yield 1/0

any(itr())  # --> True

or

class ErrorOnBool:
    def __bool__(self):
        raise RuntimeError()


any([1, ErrorOnBool()])   # --> True
Related