0

When I input

print sorted([10, 4, 2, 12, 3], key=str, reverse=True)

Why is the result:

[10, 12, 2, 3, 4]

ocket8888
  • 1,060
  • 12
  • 31
Zhang Tong
  • 4,569
  • 3
  • 19
  • 38
  • The answer [here](https://stackoverflow.com/questions/34865217/how-can-i-sort-by-single-criterion) is pretty comprehensive. – user3030010 Dec 02 '16 at 02:00
  • The result is not as you say. It's `[4, 3, 2, 12, 10]`, due to the `reverse` parameter being `True`. Regardless of this, it should be trivial to find an answer to the question using the python [documentation](https://docs.python.org/2/library/functions.html#sorted)! – Paul Rooney Dec 02 '16 at 02:31

2 Answers2

0

Because you are sorting them by their string representation, which uses lexicographical sorting: you sort by the first character, if those are the same then you compare the next one. So just like "aardvark" comes before "bee" in a dictionary, so does "10" come before "2", because the character "1" is before the character "2".

Amadan
  • 191,408
  • 23
  • 240
  • 301
0

That key sends each element to the str function for comparison purposes. When strings are sorted, they are compared alphabetically. Since '1' is before '2', '12' comes before '2', in the same way that 'and' would come before 'ball'. There is no such thing as place value in strings, as there is with numbers.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97