Python Conditions · Lesson 33 of 149

Python Chained Comparisons, Short-circuiting and the Walrus Operator

What you will learn

  • How chained comparisons like 10 < x < 20 really work, and a trap
  • What short-circuiting means for and and or
  • How to use it as a guard against errors
  • The walrus operator := (Python 3.8 and later), and where it helps

1. Chained comparisons

Python lets you chain comparisons the way mathematics does. 10 < x < 20 means "x is between 10 and 20":

x = 15
print(10 < x < 20)
print(10 < x <= 15)
print(1 < 2 < 3 < 4)
True
True
True

A chain a < b < c means a < b and b < c, with one difference: the middle value b is worked out only once.

def noisy(v):
    print("evaluating", v)
    return v

print(0 < noisy(5) < 10)
evaluating 5
True

You can mix the operators, including ==, !=, in and is:

print(1 == 1 < 2, x == 15 != 16, 1 < 3 > 2)
True True True
Quick check: what does `3 > 2 > 2` give?

False. It means 3 > 2 and 2 > 2, and the second part is false.

The trap: a chain is not a single comparison

Every neighbouring pair is tested separately. That gives odd results when the operators are unusual:

print(5 > 3 == True)
print((5 > 3) == True)
print(1 != 2 != 1)
False
True
True

Read each one carefully:

  • 5 > 3 == True is 5 > 3 and 3 == True. The second part is False, so the result is False, although (5 > 3) == True is True.
  • 1 != 2 != 1 is 1 != 2 and 2 != 1, which is True. It does not mean "all three are different": the first and the last are both 1, yet the chain is true.

To avoid confusion, use a chain only for ordering such as a < b < c, and write anything else with and.

2. Short-circuiting

and and or stop as soon as the answer is known, and skip the rest:

  • a and b: if a is false, the answer is already false, so b is not evaluated.
  • a or b: if a is true, the answer is already true, so b is not evaluated.
def t(v):
    print("t", v)
    return v

print(t(False) and t(True))
print(t(True) or t(False))
print(t(True) and t(False))
print(t(False) or t(True))
t False
False
t True
True
t True
t False
False
t False
t True
True

In the first two cases only one call was made. In the last two, both were needed.

The tool any and all also stop early. any stops at the first true item and all at the first false one, so they can work on huge or endless sources:

print(any(print("check", i) or i > 1 for i in range(5)))
check 0
check 1
check 2
True

The loop stopped at 2, the first item that made the answer True, and never looked at 3 or 4.

3. Short-circuiting as a guard

Because the second part is skipped, you can put a safety check first, and the risky part after it:

lst = []
print(len(lst) > 0 and lst[0] == 1)

den = 0
print(den != 0 and 10 / den > 1)
print(den == 0 or 10 / den > 1)

name = None
print(name is not None and name.upper())
False
False
True
False
  • If the list is empty, lst[0] would raise an IndexError, but it is never reached.
  • If den is zero, the division is skipped, so there is no ZeroDivisionError.
  • If name is None, name.upper() is never called.

The order matters. Put the check on the left:

print(name.upper() and name is not None)
AttributeError: 'NoneType' object has no attribute 'upper'

Here name.upper() runs first, and fails.

Using and/or for actions

Because the right side is skipped, you may see this style, which acts like a tiny if:

x = 5
x > 3 and print("shown")
x < 3 and print("hidden")
shown

It works, but it is cryptic. Use a normal if statement in your own programs (lesson 5.2).

4. The walrus operator

An assignment such as n = 10 is a statement: it cannot sit inside another expression. The assignment expression :=, nicknamed the walrus operator (it looks like a walrus lying on its side), assigns and gives back the value. It needs Python 3.8 or later:

if (n := len("hello")) > 3:
    print(n, "is long")
5 is long

len("hello") is worked out once, stored in n, and compared with 3. Without the walrus you would write two lines, or call len twice.

Always put brackets around it when it is part of a bigger expression:

print((y := 10) + 5, y)
15 10

Where it helps

1. Using a value in the test and in the block:

data = [1, 2, 3, 4]
if (count := len(data)) > 3:
    print(f"{count} items")
4 items

2. Testing the result of a search (the re module is lesson 17.6):

import re

if (m := re.search(r"\d+", "abc 123 def")) is not None:
    print(m.group())
123

3. Loops that read until a condition fails (while is chapter 6):

text = "a,b,c"
while (idx := text.find(",")) != -1:
    print(idx, end=" ")
    text = text[:idx] + ";" + text[idx + 1:]
print(text)
1 3 a;b;c

4. Keeping an expensive result in a comprehension (chapter 12):

vals = [1, 5, 10, 20]
print([v2 for v in vals if (v2 := v * 2) > 10])
[20, 40]

The doubled value is calculated once, tested and kept.

What the walrus cannot do

It cannot stand alone as a statement, and it needs brackets in many places:

z := 3
SyntaxError: invalid syntax

Use it sparingly: when it makes the code shorter and clearer, not just because it is possible. A normal = on its own line is easier to read.

Worked example: check a reading, safely

A sensor sends a reading as text, which may be missing. Accept it only if it is a number between 0 and 100 (made-up limits).

def valid(reading):
    return reading is not None and reading.isdigit() and 0 <= int(reading) <= 100

for r in [None, "abc", "250", "42", "100"]:
    print(repr(r), valid(r))
None False
'abc' False
'250' False
'42' True
'100' True
Step Why this order
reading is not None first, so .isdigit() is never called on None
reading.isdigit() next, so int(reading) is never called on "abc"
0 <= int(reading) <= 100 the chained comparison for the range

Each check protects the next one, thanks to short-circuiting. (def and the for loop come in later chapters.)

Common mistakes

  • Reading a < b > c as "b is the biggest of three". It only compares neighbours.
  • Using chains with == and != to mean "all equal" or "all different".
  • Putting the risky test before the safety test in an and or or.
  • Writing := without brackets inside bigger expressions.
  • Using the walrus on Python before 3.8.
  • Using x and print(...) instead of if.

Key takeaways

  • a < b < c means a < b and b < c, with b evaluated once; use chains for ranges.
  • and stops at the first false value and or at the first true one, so the right side may never run.
  • Use that to put a guard check first: lst and lst[0], den != 0 and x / den.
  • := assigns and returns a value inside an expression (Python 3.8 and later); put brackets around it.
  • Use the walrus when it avoids repeating a calculation, and not otherwise.

Practice

1. Write a single condition that is true when age is from 13 to 19, inclusive.

Show answer

13 <= age <= 19.

2. What does 1 < 5 > 3 give, and what does it mean?

Show answer

True. It means 1 < 5 and 5 > 3.

3. What is printed by print(False and print("hi"))?

Show answer

Only False. The right side is skipped, so hi is never printed.

4. Make items[0] == "x" safe when items might be empty.

Show answer

items and items[0] == "x" (or len(items) > 0 and items[0] == "x"). The safety check goes first.

5. Rewrite using the walrus: total = sum(nums) then if total > 100: print(total).

Show answer
if (total := sum(nums)) > 100:
    print(total)

6. Why must the check den != 0 come before 10 / den in den != 0 and 10 / den > 1?

Show answer

and evaluates left to right and stops when the left side is false. With den = 0 the division is skipped. If the division came first, it would raise a ZeroDivisionError.