VVV
VVV

Reputation: 47

Why does the condition "3 > 5 in range(10)" return False in python?

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

Answers (1)

CIsForCookies
CIsForCookies

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:

  1. 3 > 5 in range(10)
  2. 3 > 5 and 5 in range(10)
  3. 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:

  1. (3 > 5) in range(10)
  2. False in range(10)
  3. 0 in range(10)
  4. 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

Related Questions