Sorting using lambda not working in Py2.1?

Brian Kelley kelley at bioreason.com
Sat May 5 05:34:25 EDT 2001


Brian Quinlan wrote:

> > I may be doing something wrong, or is this a bug in 2.1?
>
> You are doing something wrong :-) From the docs:
>
> The sort() method takes an optional argument specifying a comparison
> function of two arguments (list items) which should return -1, 0 or 1
> depending on whether the first argument is considered smaller than, equal
> to, or larger than the second argument. Note that this slows the sorting
> process down considerably; e.g. to sort a list in reverse order it is much
> faster to use calls to the methods sort() and reverse() than to use the
> built-in function sort() with a comparison function that reverses the
> ordering of the elements.

It should be noted that Python 1.5.1 could handle l.sort(lambda x,y: x<y)
before the sorting engine was revamped.  This was not in line with the stated
documentation saying that a comparison operator must return -1,0,1.  Of course
I used this idiom heavily for a while and it came back to bite me in hte 1.5.2
release.   However when I reported the 'bug' there was a very insightful
thread started on sorting and what not.

If you want to know more about sorting, check out Andrew Dalke's sorting
mini-howto http://py-howto.sourceforge.net/sorting/sorting.html

Enjoy,

Brian Kelley




More information about the Python-list mailing list