Fix Python – How to sort a list of strings numerically?


Asked By – Brian

I know that this sounds trivial but I did not realize that the sort() function of Python was weird. I have a list of “numbers” that are actually in string form, so I first convert them to ints, then attempt a sort.

for item in list1:

print list1

Gives me:

['1', '10', '2', '200', '22', '23', '3', '4']

What I want is


I’ve looked around for some of the algorithms associated with sorting numeric sets, but the ones I found all involve sorting alphanumeric sets.

I know this is probably a no brainer problem but google and my textbook don’t offer anything more or less useful than the .sort() function.

Now we will see solution for issue: How to sort a list of strings numerically?


You haven’t actually converted your strings to ints. Or rather, you did, but then you didn’t do anything with the results. What you want is:

list1 = ["1","10","3","22","23","4","2","200"]
list1 = [int(x) for x in list1]

If for some reason you need to keep strings instead of ints (usually a bad idea, but maybe you need to preserve leading zeros or something), you can use a key function. sort takes a named parameter, key, which is a function that is called on each element before it is compared. The key function’s return values are compared instead of comparing the list elements directly:

list1 = ["1","10","3","22","23","4","2","200"]
# call int(x) on each element before comparing it

This question is answered By – Seamus Campbell

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0