← Python lessons

Python Comparison Operators: Chaining and Comparing Strings

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A chained comparison like 0 <= score <= 100 tests several comparisons at once, joined as if by and.

Read Comparisons and Logical Operators first.

Check a range in one expression

score = 75
print(0 <= score <= 100)
print(score >= 0 and score <= 100)

Both lines print True. Python reads a <= b <= c as a <= b and b <= c, and it works out b only once.

Read a chain left to right

Each operator compares its two neighbours only. The first and last values are never compared directly.

print(1 < 5 > 2)
print(3 == 3 == 3)
print(1 < 3 > 2 < 9)

All three print True. 1 < 5 > 2 means 1 < 5 and 5 > 2. It says nothing about 1 and 2. Long mixed chains like the last one are legal but hard to read, so use them for ranges only.

Note: x == y == z checks that all three are equal. x != y != z does not check that all three differ: 1 != 2 != 1 is True.

Compare strings in alphabetical order

< and > also work on strings. Python compares them character by character, by each character's code number (ord()).

print("apple" < "banana")
print("Zebra" < "apple")
print("app" < "apple")
print(ord("Z"), ord("a"))

This prints True, True, True, then 90 97. Every capital letter comes before every lowercase letter, so "Zebra" sorts first. A shorter string that matches the start of a longer one comes first.

To check one character is a lowercase letter, chain on characters:

letter = "q"
print("a" <= letter <= "z")
print("a" <= "Q" <= "z")

The first prints True, the second False.

Comparing different types

== between a number and a string is just False. Ordering them raises an error.

print(5 == "5")
try:
    print(5 < "6")
except TypeError as error:
    print("TypeError:", error)

Convert first with int() when the text holds a number. This lesson leaves out locale-aware sorting and accented letters, which need more than <.

See also: Data Validation, Sorting.

Your turn

For each word in words, print the word and whether it falls between "cat" and "fox" (inclusive) in alphabetical order. Use one chained comparison.

words = ["dog", "ant", "fox", "Elk"]
for word in words:
    # print the word and one chained comparison
    pass

Expected output

dog True
ant False
fox True
Elk False