'10' < '9' is True
'10' < '9' is True in Python means strings compare character by character, like a dictionary. "1" comes before "9", so "10" sorts before "9" whatever follows.
How do I fix '10' < '9' is True?
In Python, '10' < '9' is True because strings compare character by character, and "1" comes before "9". Numbers read from files, forms or input() are text until converted. Convert with int() or float() before comparing, or pass key=int to max() and sorted(). For versions, compare lists of ints.
- 1. Check the typePrint type(value). If it is str, the comparison is alphabetical, not numeric.
- 2. Use key=intWrite max(values, key=int) or sorted(values, key=int) when the list holds numeric strings.
- 3. Version stringsCompare [int(x) for x in v.split(".")] lists, or use packaging.version.Version, not the raw strings.
What does '10' < '9' is True mean?
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.
Why does '10' < '9' is True happen?
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" # FalseWorks
def parts(v):
return [int(x) for x in v.split(".")]
parts("10.0") > parts("9.4") # TrueHow 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
mediumhighest(["9", "10", "2"]) returns "9".
def highest(values):
return max(values)More challenges with this error
Each of these challenges runs into this error. Find the bug and fix it, no install and 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.