2
>>> 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).

ShadowRanger's user avatar
ShadowRanger
158k12 gold badges222 silver badges317 bronze badges
askedSep 24, 2019 at 16:14
warvariuc's user avatar
4
  • Chaining works with any comparison operator,a op b op c is equivalent to(a op b) and (b op c)CommentedSep 24, 2019 at 16:20
  • With the slight difference in behavior thata op b op c only has to compute/loadb once, 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.CommentedSep 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)CommentedSep 24, 2019 at 16:33
  • @Massifox: Incorrect. All the comparison operators (aside from boolean operatorsor,and andnot)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).CommentedSep 24, 2019 at 16:34

1 Answer1

0

python is correcting your comparison automatically with if (b>a) AND (a==c)

answeredSep 24, 2019 at 16:19
Eirik Fesker's user avatar
Sign up to request clarification or add additional context in comments.

4 Comments

"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.
"and likely a programmer mistake". That's the thing: PyCharm suggests to simplifya < b and c == a and it looks wrong.
@warvariuc: The PyCharm simplification is largely correct (aside froma < 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).
@ShadowRanger Seeyoutrack.jetbrains.com/issue/PY-37991 That's where my question came from.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.