This question already has answers here:
Hidden features of Python [closed] (191 answers)
Why does the expression 0 < 0 == 0 return False in Python? (How are chained comparisons interpreted?) (9 answers)
Closed6 years ago.
>>> a = 2>>> b = 3>>> c = 2>>> b > a == cTrue>>>Is this true thatb > a == c is equal toa < b and c == a because it's a chained comparison?
This doesn't make sense to me because of== comparison, I would expect thatb > a == c is equal to(b > a) == c orb > (a == c).
- Chaining works with any comparison operator,
a op b op cis equivalent to(a op b) and (b op c)Barmar– Barmar2019-09-24 16:20:59 +00:00CommentedSep 24, 2019 at 16:20 - With the slight difference in behavior that
a op b op conly has to compute/loadbonce, where(a op b) and (b op c)would have to do so twice. Specific answer on duplicate that addresses your problem isChaining comparison operators.ShadowRanger– ShadowRanger2019-09-24 16:24:10 +00:00CommentedSep 24, 2019 at 16:24 - According to the comment from @Barmar operator priority doesn't work in this case, because it's a chained comparison which results to
(a < b) and (c == a)warvariuc– warvariuc2019-09-24 16:33:16 +00:00CommentedSep 24, 2019 at 16:33 - @Massifox: Incorrect. All the comparison operators (aside from boolean operators
or,andandnot)have equal precedence. The parentheses simply prevent the chaining from operating at all, so you simply have one unchained comparison within the parentheses, with the result used in an unchained comparison outside the parentheses).ShadowRanger– ShadowRanger2019-09-24 16:34:27 +00:00CommentedSep 24, 2019 at 16:34
1 Answer1
python is correcting your comparison automatically with if (b>a) AND (a==c)
Sign up to request clarification or add additional context in comments.
4 Comments
ShadowRanger
"correcting" implies the code was wrong in some way and Python had to fix it. The Python language spec intentionally supports this design; it's just unusual (and likely a programmer mistake) to use it to chain greater-than with equality testing.
warvariuc
"and likely a programmer mistake". That's the thing: PyCharm suggests to simplify
a < b and c == a and it looks wrong.ShadowRanger
@warvariuc: The PyCharm simplification is largely correct (aside from
a < b possibly behaving differently fromb > a, same fora == c vs.c == a). It has to loada twice, but it's less confusing. If the PyCharm simplification is wrong, it probably means you didn't write what you intended, and need additional parentheses to correct it to(b > a) == c orb > (a == c) (assuming one of those was the intent). Comparison chaining is much more intuitive for stuff like range testing, e.g.if 0 < x < 10: as a simple way to check ifx is between0 and10 (exclusive).warvariuc
@ShadowRanger Seeyoutrack.jetbrains.com/issue/PY-37991 That's where my question came from.
Explore related questions
See similar questions with these tags.

