I have this list A
:
A = ['-1', '-2', '-2', '1', '1', '10', '100', '20', '4']
if i put sorted(A)
this i get
['1', '1', '-1', '20', '4', '-2', '-2', '10', '100']
I tried this list:
lista = ['3', '2', '5', '6', '7']
and if I repeat this process, that is sorted(lista)
, it prints it sorted but, for some reason, I have problems with negative numbers. I don't understand why Python doesn't order it properly anymore.
What I needed was for me to organize a list of string numbers, without the need to return them to integers and without using any loops .
Any idea why this is happening and if it can be fixed?
Since your list is a list of strings, Python sorts them as strings using
codepoints
unicode. This causes, for example, '103' to be considered less than '3', since '1' is less than '3'.If you don't want to pass your list to integers, just use the argument
key
ofsort
:Or with
sorted
:Note that it
sorted
returns a new list, sorted copy of the original, while itlist.sort
sorts the original list directly.