sorting a list numbers stored as strings

Delaney, Timothy (Tim) tdelaney at avaya.com
Mon Sep 24 07:58:43 EDT 2007


Carsten Haese wrote:

> That interpreter session is a work of fiction, since sorted returns
> the sorted list instead of sorting the list in place. Also, it's
> better (i.e. more readable and likely faster) to use a sort key
> function instead of a comparison function whenever possible. In this
> case, the sort key function is particularly trivial:
> 
>>>> l = ["1", "11", "2", "22"]
>>>> sorted(l, key=int)
> ['1', '2', '11', '22']

It does appear trivial in this case, but need to be careful with using
int() if any of the strings could have leading zeros. In this case, the
fix is almost as trivial:

>>>> l = ["01", "11", "08", "22"]
>>>> sorted(l, key=lambda x: int(x, 10))
> ['01', '08', '11', '22']

Although I just tried the above using just sorted(l, key=int) and it
succeeded. I'm sure that in some version of Python it would have given a
ValueError (due to the default radix being 0) but it appears to have
changed to a default radix of 10 somewhere along the way. The docs don't
specify what the default radix is (I should probably raise a bug report
for this).

Tim Delaney



More information about the Python-list mailing list