Python 1.5.2 list sorting bug

Tim Evans tre17 at student.canterbury.ac.nz
Thu Oct 28 20:16:59 EDT 1999


Brian Kelley <kelley at bioreason.com> writes:

> Christian Tismer wrote:
[snip] 
> but I can assure you that now it has become:
> 
> a.sort(lambda x,y: cmp(y, x) ) and
> a.sort(lambda x,y: cmp(x,y) )
> 
> or better yet forming the appropriate tupes and using a normal sort.
> 

Substitute:

a.sort(lambda x,y: cmp(y,x))   ====>   a.sort()
a.sort(lambda x,y: cmp(x,y))   ====>   a.sort(); a.reverse()

According to 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.
'''

So don't provide your own function, especially a lambda when you don't
need to, and get a reverse sorted list by sorting and reversing.

--
Tim Evans





More information about the Python-list mailing list