4

Can someone explain to me why the Python interpreter evaluates this expression to be False?

1 in [1] == True

I would expect that 1 in [1] would evaluate to True, and obviously True == True would be True. However this isn't what happens - the expression is False. Why does this happen?

2 Answers2

11

== and in are both comparison operators. And when you have multiple comparison operators like this, Python considers it a chained comparison. For example, 1 < x < 10 is equivalent to 1 < x and x < 10.

In your case, 1 in [1] == True is equivalent to (1 in [1]) and ([1] == True), which evaluates to False.

interjay
  • 107,303
  • 21
  • 270
  • 254
1

If you have an expression like this python split it to more statements. In fact:

1 in [1] == True equals to: (1 in [1]) and ([1] == True)

Right side is false since [1] != True and whole sentence is false

Relandom
  • 1,029
  • 2
  • 9
  • 16