I was just messing around in the Python interpreter and I came across some unexpected behavior.
>>> bools = (True, True, True, False)
>>> all(bools)
False
>>> any(bools)
True
Ok, so far nothing out of the ordinary...
>>> bools = (b for b in (True, True, True, False))
>>> all(bools)
False
>>> any(bools)
False
Here's where things start getting spooky. I figure this happens because the all
function iterates over the generator expression, calling its __next__
method and using up the values until it encounters one that is False
. Here's some evidence to back that theory up:
>>> bools = (b for b in (True, False, True, True))
>>> all(bools)
False
>>> any(bools)
True
I think the result is different because the False
is not at the end, so there are still some unused values left in the generator. If you type
>>> bools = (b for b in (True, False, True, True))
>>> all(bools)
False
>>> list(bools)
[True, True]
It seems like there are only 2 remaining values.
So, why exactly does this really happen? I'm sure there are many details that I'm missing.