BugHunt

'10' < '9' is True

Strings compare character by character, like a dictionary. "1" comes before "9", so "10" sorts before "9" whatever follows.

PythonType errors

What it means

Numbers read from files, forms and version strings are text until you convert them. max(), sorted() and < on text use alphabetical order, which only matches numeric order when every value has the same number of digits.

Common causes

1. max() or sorted() on numeric strings

Alphabetical order puts "9" after "10".

Breaks

max(["9", "10", "2"])   # '9'

Works

max(["9", "10", "2"], key=int)   # '10'

2. Comparing version numbers

Each part is a number, not a character.

Breaks

"10.0" > "9.4"   # False

Works

def parts(v):
    return [int(x) for x in v.split(".")]
parts("10.0") > parts("9.4")   # True

How to find it in your own code

Convert where the data enters the program, or compare with key=int (or key=float). For versions, compare lists of ints, or use packaging.version.Version.

Try it: fix this bug

medium

highest(["9", "10", "2"]) returns "9" instead of "10".

def highest(values):
    return max(values)
Open with hintsRuns in your browser. No account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Other common errors