-3
>>> '10'>'3'
False
>>>
>>> a=['10','9','8','7']
>>> a.sort()
>>> a
['10', '7', '8', '9']

Why is '10' less than '3' ? I tried with several more values but the same thing is happening with it.

>>> '10'>'3'
False
>>>
>>> a=['10','9','8','7']
>>> a.sort()
>>> a
['10', '7', '8', '9']
>>>

I expect the output of '10'>'3' to be True.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

3 Answers3

1

Since you are comparing the values as strings in which each character in the first string is checked against the same index character in the second string, the results will be different. For example, comparing '10' and '3', the '1' would be placed before the 3 therefore the string '10' will be placed before '3' when ordered.

If you want to compare them as numbers, you'll have to remove the apostrophes that surrounds them:

>>> 10>3

insetad of:

>>> '10'>'3'
Omari Celestine
  • 1,405
  • 1
  • 11
  • 21
1

To see what's going on here simply try ord():

ord('1')
49
ord('7')
55

so '10' > '7' becomes 49 > 55 and that's obviously false.

meissner_
  • 556
  • 6
  • 10
0

At the moment you are comparing the string representation of the numbers you want to compare with each other.

If you leave out the quotation marks around the numbers you should be good to go. Then the numbers are interpreted as integers.