Python traps · Python

Python: "10" > "9" is FALSE?!PRO

Watch the video

Strings compare letter by letter, so "1" sorts before "9". Convert with int() first.

# "10" > "9" is False ?!
# Strings compare letter by letter, like a dictionary: "1" comes before "9".
print("10" > "9")             # False ?!
print(sorted(["10", "9", "2"]))   # ['10', '2', '9'] ?!

# Fix: turn them into numbers first
print(int("10") > int("9"))   # True ✓
print(sorted(["10", "9", "2"], key=int))   # ['2', '9', '10'] ✓
Open code P7 in Pocket Compiler Download the Pocket Compiler app — free

No app yet? Install it, then open the app and type the code P7 in Code Library.