[Tutor] Sorting a list

Lie Ryan lie.1296 at gmail.com
Thu May 14 15:13:43 CEST 2009


Timo wrote:
> Hello,
> 
> I don't think this should be difficult, so maybe I look over it. But I 
> can't seem to find the solution.
> 
> I have a list with one word and a couple of numbers. Now I want the word 
> to be kept in the first location and the numbers to be sorted.
> 
> So this:
> [4, 6, 'word', 3, 9]
> 
> should be:
> 
> ['word', 3, 4, 6, 9]
> 

Why not:
 >>> sorted(lst, key=lambda x: (0, x) if isinstance(x, str) else (1, x))
['word', 3, 4, 6, 9]

I think sorting tuple has a well-defined meaning, i.e. sort on first 
item, then second, then third, etc... and there is AFAIK no restriction 
that the key argument should be a number right?



More information about the Tutor mailing list