I am trying to sort the following data in a CSV file:

list_all = ["10","2","113.2","200"]

Sounds simple, right? So I use the following codes to sort it:

list_all = ["10","2","113.2","200"]
sortedlist = sorted(list_all)

But it doesn't work properly.

This is the output from my function.

['10', '113.2', '2', '200']

Apparently, it is sorted by the first word in each string only, which is weird. How to solve this?

5 Answers

Mureinik On Best Solutions

The elements in that lists are strings, so they are sorted lexicographically. If you want to sort them by their numeric values, you could use a custom sorting key:

sorted(list_all, key = lambda x : float(x))

As aws_apprentice commented, you could just pass a function as the sorting key and make this call a bit more concise:

sorted(list_all, key = float)
alimzoo On

Python interprets anything inside quotations ' or double quotations " as the String type. So the numbers you have written are not numbers, are just words!


on strings then, works according to the characters. Just remove the quotations:

list_all = [10,2,113.2,200]
Community On

You are trying to sort str types, not int or float.

>>> list_all = [10,2,113.2,200]
>>> sortedlist = sorted(list_all)
>>> print(sortedlist)
[2, 10, 113.2, 200]
Henrique On

Try this:

list_all = ["10","2","113.2","200"]
list_all.sort(key = float) 
Filip MÅ‚ynarski On

It's because its sorting its contents like strings (because that's what they are), you could sort them to by their float representation using sorted argument key.

list_all = ["10","2","113.2","200"]
sortedlist = sorted(list_all, key=float)

print(sortedlist) # --> ['2', '10', '113.2', '200']