When I input
print sorted([10, 4, 2, 12, 3], key=str, reverse=True)
Why is the result:
[10, 12, 2, 3, 4]
When I input
print sorted([10, 4, 2, 12, 3], key=str, reverse=True)
Why is the result:
[10, 12, 2, 3, 4]
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".
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.