Reputation: 47
I'm unable to understand the logic behind python returning False
for the following condition:
3 > 5 in range(10)
while returning True
for:
False in range(10)
Upvotes: 0
Views: 206
Reputation: 12837
Although the comment by @jonrsharpe is the right answer, it wasn't trivial to me, and maybe also to you, so I'll break it down:
The expression is evaluated like this:
3 > 5 in range(10)
3 > 5 and 5 in range(10)
False and 5 in range(10) == False
(False and ...
short circuits to False
)The reason for 1 -> 2
is explained in the documentation. To sum it up, it's like x < y < z
means x < y
and y < z
.
Trying something like (3 > 5) in range(10)
would be evaluated like this:
(3 > 5) in range(10)
False in range(10)
0 in range(10)
True
The reason for 3 -> 4
is that 0
resides inside the range(0,10)
and the expression 0 in range(10)
is evaluated to a Boolean result (i.e. True
or False
) depends on whether the left side (0
) is indeed in the right side (range(0,10)
)
Upvotes: 5