2

I might be missing something obvious here, but why does Python 2.x sorted() function work like this?

In [95]: l = [1, '5', 4, 2, '3', 'b', 'c', '-a']
In [96]: sorted(l)
Out[96]: [1, 2, 4, '-a', '3', '5', 'b', 'c']

Python 3 returns exception (TypeError: unorderable types: str() < int()), which I expect more than this result.

2

It looks like the ASCII values of the characters are used to sort relative to the actual numbers.

After converting the characters to their decimal ASCII values, the sorted list looks something like this:

[1, 2, 4,  '-a', '3', '5', 'b', 'c']
[1, 2, 4, 45 97,  51,  53,  98,  99]

Note that '-a' is sorted by the first character first, as is normal for an "alphabetical" ordering.

  • So they are silently converted to the textual representation of their numerical character encodings. What a wonderful demonstration that indeed, explicit is better than implicit. – Ryan Reich Nov 4 '15 at 22:04
  • 2
    No, there's no silent conversion going on. The numbers all compare less than the strings, so we get all the numbers (in sorted order), followed by all the strings (in their usual lexicographic order based on the underlying ASCII encoding). If you try adding the number 999 to the list (for example), you'll see that in the sorted output it'll end up after all the other numbers, and before all the strings. – Mark Dickinson Nov 6 '15 at 8:36
  • For more info, see: stackoverflow.com/questions/3270680/… – Mark Dickinson Nov 6 '15 at 8:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.