tags:

views:

122

answers:

2

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?

+11  A: 

When you pass a lambda to sort, you need to return an integer, not a boolean. So your code should instead read

xs.sort(lambda x,y: cmp(len(x), len(y))

Note that cmp is a builtin function such that cmp(x, y) returns -1 if x is less than y, 0 if x is equal to y, and 1 if x is greater than y.

Of course, you can instead use the key parameter:

xs.sort(key = lambda s: len(s))

This tells the sort method to order based on whatever the key function returns.

EDIT: Thanks to balpha and Ruslan below for pointing out that you can just pass len directory as the key parameter, thus eliminating the need for a lambda:

xs.sort(key = len)

And as Ruslan points out below, you can also use the built-in sorted function rather than the list.sort method, which creates a new list rather than sorting the existing one in-place:

print sorted(xs, key=len)
Eli Courtwright
+1 for the solution with the `key` argument.
Jacek Konieczny
No need for the `lambda`; just use `key = len`
balpha
+6  A: 

The same as in Eli's answer - just using a shorter form, because you can skip a lambda part here.

Creating new list:

>>> xs = ['dddd','a','bb','ccc']
>>> sorted(xs, key=len)
['a', 'bb', 'ccc', 'dddd']

In-place sorting:

>>> xs.sort(key=len)
>>> xs
['a', 'bb', 'ccc', 'dddd']
Ruslan Spivak