Sorting using lambda not working in Py2.1?

Tim Peters tim.one at home.com
Fri May 4 19:59:29 CEST 2001


[Brian Kelley]
> 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 is false.  What was true is that passing x<y used to be more likely to
work by accident, and especially for small lists.  Python's sort() has
*always* required a 3-outcome cmp function, and people passing x<y in earlier
Pythons eventually suffered horrid surprises as their data changed and their
lists got larger.

In a similar vein, the current sort happens to be stable for small lists, but
isn't stable in general.

> This was not in line with the stated documentation saying that a
> comparison operator must return  -1,0,1.

The docs were correct, although the implementation only distinguished among
<0, ==0, and >0.

If we had it to do all over again, I bet sort() would require a < function
instead of a cmp() one.  The reason it required cmp() at the start was simply
because libc's qsort() function requires a 3-outcome cmp, and Python used
libc for sorting.  That proved impossible to live with, though, and as soon
as Python grew its own sorting smarts the only reason to stick with cmp() was
for backward compatibility.  And contrary to persistent rumor, Guido doesn't
change things gratuitously <wink>.





More information about the Python-list mailing list