If the list should save strings but you want to sort by numerical values, it is interesting to insert values only if they are numbers. For this you can use int
to convert the string to number, and capture the ValueError
if it is not (because if it is not a number, it makes no sense to try to sort by the numerical value).
lista = ['0']
while True:
n = input('digite aqui: ')
try:
int(n) # tenta converter para número
lista.append(n)
print(sorted(lista, key=int)) # ordena a lista pelo valor numérico
except ValueError:
print('Não foi digitado um número')
I did so because it seems that you want the list to have strings (since in the output the numbers are in quotes).
But why did I do all this if a another answer seems to have worked? Well, you probably should only have tested with one-digit numbers. For sorting strings this way hides some traps. Ex:
lista = ['1', '2', '10']
lista.sort()
print(lista) # ['1', '10', '2']
Note that the 10
came before the 2
. This is because strings are composed of characters, and even digits are considered characters, and the ordering takes into account their lexicographic order, not their numerical values (in this question has a more detailed explanation - although it is in Javascript, the concepts are basically the same and will help you understand why the 10
came before the 2
in ordination).
If you only test with one-digit numbers, the problem does not appear. But it is an important detail to look at.
Already doing key=int
, i convert the strings to their respective numeric value, and this is considered in the sort. That is:
lista = ['1', '2', '10']
lista.sort(key=int)
print(lista) # ['1', '2', '10']
Another difference is that in the first example I used sorted
, does not modify the original list. Already lista.sort
modifies the list itself (i.e., depending on what you need, using one or the other makes a difference).
Although I don’t think it’s very efficient to sort the list all the time. If you always need to show it in an orderly fashion, an alternative is to ensure that the elements are always in order.
For this we can use the module bisect
, which has methods - such as the insort
- to insert in an orderly manner into the list:
from bisect import insort
lista = [0]
while True:
try:
insort(lista, int(input('digite aqui: ')))
print(lista)
except ValueError:
print('Não foi digitado um número')
Thus, the elements will always be in order, simply print the list directly.
Another difference is that the list now contains numbers instead of strings (i.e., they are printed without the quotes). If you really want them to be printed as strings, you can convert them when printing print(list(map(str, lista)))
instead of just print(lista)
.