The problem is on this line:
...
lista.remove(lista[-1])
...
It’s because of the fact that remove()
remove the first occurrence of the element, i.e., for inputs, "2,2,5,2
", obtained:
2
2
2
5
On the first lap you’re apparently eliminating the last element: remove(lista[-1])
, which in this case remains remove(2)
, BUT, this 2 that will be removed will be the first and not the last:
remove(x)
Remove the first item from the list Whose value is x.
Translation
Removes the first item from the list whose value is x.
DOCS
Or whatever will happen to your list along your second loop while
is:
[2, 2, 5, 2, 0]
[2, 2, 5, 2]
[2, 5, 2]
[5, 2]
[5]
And the prints of lista[-1]
which in this case will be:
2
2
2
5
(do not forget that 0 was deleted before the first print)
If you allow me I will present a suggestion for improvement (to do exactly this) without modifying your code too much:
lista = []
n = int(input("Digite um número: "))
while n != 0:
lista.append(n)
n = int(input("Digite um número: "))
while lista: # enquanto houverem elementos na lista, equivalente a while len(lista) > 0
ele = lista.pop() # retirar o ultimo elemento da lista
print(ele)
POP DOCS()
Or if you prefer to delete it by index:
lista = []
n = int(input("Digite um número: "))
while n != 0:
lista.append(n)
n = int(input("Digite um número: "))
while lista: # enquanto houverem elementos na lista, equivalente a while len(lista) > 0
ele = lista[-1]
del lista[len(lista)-1]
print(ele)
And we can even go further, if the goal is just to print and remove the inputs that are in the list in reverse order we can delete the second while and take the Casts to int:
lista = []
n = input("Digite um número: ")
while n != '0':
lista.append(n)
n = input("Digite um número: ")
print('\n'.join(reversed(lista)))
lista.clear()
What’s supposed to happen? Here it seems to be working fine... Returns in reverse order
– Miguel
Note the number "5" it changes order, if you put a print(list) can be better visualization.
– Mário Rodeghiero
Take a look at this link
– Solkarped