[Python-bugs-list] list.sort() with sort function (PR#131)

tim_one@email.msn.com tim_one@email.msn.com
Thu, 18 Nov 1999 02:08:52 -0500 (EST)


> Full_Name: Sam Rushing
> Version: 1.5.2
> OS: linux, bsd
> Submission from: s0-106-a-gte.br5.blv.nwnexus.net (206.63.253.91)
>
>
> list.sort() with a sort function appears broken.
>
> >>> l = [23, 342, 17]
> >>> l
> [23, 342, 17]
> >>> l.sort (lambda a,b: a > b)
> >>> l
> [23, 342, 17]
> >>>

Not a bug.  Amazingly enough, see thread "Python 1.5.2 list sorting bug"
from just a couple weeks ago (on comp.lang.python) for detailed discussion.

Short course:  unless you're trying to be excruciatingly clever, as the docs
say the sort function must be cmp-like, returning -1 (anything < 0) for <, 0
for ==, +1 (anything > 0)for >.  "a > b" returns 0 for a <= b, so confuses
equality with inequality.

If the intent of the above was to sort in reverse order,

>>> l.sort(lambda a, b: cmp(b, a))
>>> l
[342, 23, 17]
>>>

or, quicker,

>>> l.sort()
>>> l.reverse()
>>> l
[342, 23, 17]
>>>