Skip to the solution
EasyDSA5 min read

How does comparison chaining (a < b < c) work?

350 views

The problem

Question presented to candidate: "In Python you can write 0 <= x < 10. What does the interpreter actually do with that, and why is 3 > 2 > 1 True while (3 > 2) > 1 is False?"

What a strong answer should cover:

  • a < b < c means (a < b) and (b < c), not (a < b) < c; every comparison operator chains this way, including ==, !=, is, is not, in and not in.
  • The middle operand is evaluated once, operands are evaluated left to right, and the chain short-circuits: c is never evaluated when a < b is false.
  • A chain only compares neighbours: 1 < 3 > 2 is legal and True, and says nothing about how 1 and 2 relate.
  • Gotchas from mixing operators: 1 in [1, 2] == True is False, False == False in [False] is True.
  • CPython detail: the chain keeps the middle value on the stack (SWAP/COPY in dis) and calls bool() on each intermediate result, which is why NumPy arrays raise "truth value is ambiguous" in a chain.

Code / implementation expected: Optional β€” a range check, plus a side-effect function showing each operand is evaluated once.

  • operators
  • chaining

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonChaining rules, the parentheses trap and mixed operators
PythonEvaluated once, short-circuit, and bool() on each step

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 28 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

What do enumerate and zip do?

Continue