David Liu
David Liu

Reputation: 507

Why does True == True evaluate to True, when {a statement that's equal to True} == True evaluates to false?

I'm having trouble explaining the contents of this script in Python3:

x = "hello"
y = "ll"
x in y == True # evaluates to False
y in x == True # evaluates to False
y in x # evaluates to True

Is there something I'm missing?

Upvotes: 0

Views: 83

Answers (1)

Salem
Salem

Reputation: 14887

You need to use parentheses:

(y in x) == True # evaluates to True

enter image description here

All comparison operators have the same precendence and are therefore evaluated left-to-right.

Chained comparisons in python have the property that:

a OP1 b OP2 c

(6.10 Comparisons)

is the same as

a OP1 b and b OP2 c

meaning that

y in x == True

evaluates to

y in x and x == True

which becomes

True and False

which is False.

I believe comparison chaining was originally introduced to allow expressions like a < b < c to have the more conventional mathematical meaning, though with == and in, it is arguably less meaningful.

Upvotes: 3

Related Questions