I want to sort a list of strings based on the string length. I tried to use sort as follows, but it doesn’t seem to give me correct result.
xs = ['dddd','a','bb','ccc']
print xs
xs.sort(lambda x,y: len(x) < len(y))
print xs
['dddd', 'a', 'bb', 'ccc']
['dddd', 'a', 'bb', 'ccc']
What might be wrong?
When you pass a
lambdatosort, you need to return an integer, not a boolean. So your code should instead read as follows:Note that cmp is a builtin function such that
cmp(x, y)returns -1 ifxis less thany, 0 ifxis equal toy, and 1 ifxis greater thany.Of course, you can instead use the
keyparameter:This tells the
sortmethod to order based on whatever the key function returns.EDIT: Thanks to balpha and Ruslan below for pointing out that you can just pass
lendirectly as the key parameter to the function, thus eliminating the need for alambda:And as Ruslan points out below, you can also use the built-in sorted function rather than the
list.sortmethod, which creates a new list rather than sorting the existing one in-place: