Sort documentation inaccurate?
Bruce Dawson
comments at cygnus-software.com
Wed Sep 26 02:03:38 EDT 2001
Or is it the implementation that is peculiar?
I'm using PythonWin 2.1 and I tried specifying a user compare function
to the list sort() function (so that I could sort file names based on
the numerical ordering instead of alphabetical) and I had difficulty
getting it working. I assumed without reading the docs carefully (if you
search the PythonWin docs for sort you get sparse information anyway)
that I could just return the result of a comparison, thusly:
>>> mylist = [1, 2, 3, 5, 4, 6]
>>> def compare1(x, y):
... return x < y
...
>>> mylist.sort(compare1)
>>> mylist
[1, 2, 3, 5, 4, 6]
but it doesn't work. It leaves the list unchanged. Bummer.
A few days later (after writing a bubble sort - good thing I had a small
list) I was typing in PythonWin when the tooltip for sort() popped up
and it said that the return value for the compare function should be 0
or *negative* 1. So I tried this:
>>> mylist = [1, 2, 3, 5, 4, 6]
>>> def compare2(x, y):
... return -(x < y)
...
>>> mylist.sort(compare2)
>>> mylist
[1, 2, 3, 4, 5, 6]
and it works!
On closer inspection the documentation says that the compare function is
supposed to return -1, 0 or 1. However this seems to be either
unnecessary, inaccurate, or both, since returning zero and one had no
effect, and returning 0 and -1 sorts the list perfectly.
Next time I'll have to read the docs more carefully, but somehow it
feels like this could be done better.
The behaviour certainly *feels* curious - having to return -(x < y) is a
trifle inelegant, and the 'correct' return value of:
if x > y:
return 1
return -(x < y
is cumbersome. In qsort() in the C library the preferred return method
is obviously something like:
return x - y;
but according to both sets of documentation that is illegal in Python,
since they specify -1, 0, 1 explicitly.
For what it's worth...
More information about the Python-list
mailing list