More rants on a bad sort

Lulu of the Lotus-Eaters mertz at
Mon Apr 28 18:13:40 CEST 2003

|>     [u'x', 'x', chr(255)].sort()
|>     ['x', chr(255), u'x'].sort()
|>     [1j, '1', 1].sort()
|>     [1, 1j, '1'].sort()

|I must admit I was surprised that 3 of these failed to sort, since I'd
|guessed that you would have selected 2 that worked and 2 that failed. So my
|question is, did one of the last two actually work on your system?

It was a trick question in that respect too.

But the problem is that I honestly do not even UNDERSTAND why .sort()
does what it does here.  If we start from the premise that some things
are comparable, and other things are not, then we can observe that:

    >>> u'x' < 'x', 'x' < chr(255)
    (0, 1)


    >>> u'x' < chr(255)
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    UnicodeError: ASCII decoding error: ordinal not in range(128)

The sorting algorithm winds up only performing allowed comparisons in:

    [u'x', 'x', chr(255)].sort()

Well... OK.  We have a similar story with complex numbers:

    >>> '1' < 1, 1j < '1'
    (0, 1)
    >>> 1 < 1j
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    TypeError: cannot compare complex numbers using <, <=, >, >=

Given all that, is it POSSIBLE to construct a list containing a string,
int, and complex, that will not crash on a sort?  I don't know!  I
couldn't find one--and I THINK the relative order of complex and strings
precludes it... but actually proving this one way or another is
decidedly non-obvious.

Yours, Lulu...

---[ to our friends at TLAs (spread the word) ]--------------------------
Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego
White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad
---[ Postmodern Enterprises <mertz at> ]--------------------------

More information about the Python-list mailing list