1

While doing some coding challenges I ran across a very strange language quirk. The program I was writing was a lowest number finder. So basically you inputted a list of numbers and the program returned the lowest number. All went well for a while, like I said its a rather basic program, but when I started to input 2 or 3 digit numbers, the Boolean logic seemed to break down. Out of a list of 2 digit and 1 digit numbers like:
x = [10, 5, 10]

the program would return 10 as the lowest number. But in a regular 1 digit list the correct lowest value would be returned. So eventually I figured out that the bug was because I forgot to convert the string type to an integer type and once that was fixed the program ran flawlessly. But that still leads to an interesting question, why did Python believe that "10" was less than "5" but "9" was greater than "5"? To deliberately prove that Python believes that fact and it was not some outside factor in my program, I opened up a python interpreter and physically entered "10" < "5" and the interpreter returned True. Any ideas why this would be happening? Thank you in advance!

Mr. Foots
  • 330
  • 2
  • 11
  • Strings are compared based on alphabetical order. There is no evaluation for "10" or "5" - they are strings just like "a", "ab", ... Otherwise, how would you answer `"10" < "a"`? – Jared Dec 28 '14 at 05:04
  • https://docs.python.org/2.7/reference/expressions.html#not-in – wwii Dec 28 '14 at 05:04
  • possible duplicate of [String Comparison Technique Used by Python](http://stackoverflow.com/questions/4806911/string-comparison-technique-used-by-python) – davelupt Jan 23 '15 at 17:50

2 Answers2

3

Python uses dictionary order aka Lexicographical Order when comparing strings, even if the strings only contain digits.

In a dictionary, "adam" < "eve" because "a" < "e". Similarly, "10" < "5" because "1" is less than "5".

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
1
"10" < "5" 

because

"1" < "5"

the same as how with english

"at" < "i"

in alphabetical order.

jamylak
  • 128,818
  • 30
  • 231
  • 230