Roman Pekar explains how you should do this.
But why does your version work?
There are two different things named cmp
here:
a.sort(cmp=lambda x,y:cmp(len(x),len(y)))
First, that cmp=
means you're passing a function as a keyword argument named cmp
. As the docs explain (in note 8):
cmp specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.
Second, what you're passing to that is a wrapper around the builtin cmp
function, which does this:
Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.
So, you're saying that to compare two list items x
and y
, it should call cmp(len(x), len(y))
. In other words, sort them by length.
If you don't understand how lambda x, y: cmp(len(x), len(y))
means that…
A lambda
expression is just a way of defining simple functions in the middle of an expression. This:
lamdba a, b, c: <some expression>
… defines the exact same function as:
def f(a, b, c): return <expression>
… except that it doesn't have a name, and can be used in the middle of an expression. So, your lambda
is the same as:
def f(x, y): return cmp(len(x), len(y))
The Lambda forms section of the tutorial explains this… although not in any more depth, and the Lambdas section of the reference docs is only slightly more detailed.
As gnibbler and Roman both point out, using cmp
instead of key
is deprecated (and illegal, in Python 3), and shouldn't be done unless you really need to work with Python 2.3 or earlier.
As gnibbler also points out, using lambda
when you don't need to is a recipe for confusion.
So, Roman's answer is exactly what you should do instead of this.
The Sorting HowTo in the docs has a nice explanation of all of this.