Reputation: 507
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
Reputation: 14887
You need to use parentheses:
(y in x) == True # evaluates to True
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
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