Python: problem with list

1

Would anyone know how to explain and how to fix the problem in the output below when I use repeated numbers? Thank you! The return must be presented in reverse and without displaying the "0"

lista=[]n=int(input("Digite um número: "))
while n != 0:
    lista.append(n)
    n = int(input("Digite um número: "))
    if n == 0:
        lista.append(n)

i = 0
while i < len(lista):
    if len(lista) <= 1:
        break
    lista.remove(lista[-1])
    print(lista[-1])
    
asked by anonymous 28.02.2017 / 23:21

1 answer

1

The problem lies in this line:

...
lista.remove(lista[-1])
...

This is because% with% remove the first occurrence of the element, ie for inputs, " remove() ", I get:

  

2 of 2
2 of 5

In the first round you seem to be removing the last element: 2,2,5,2 , which in this case is remove(lista[-1]) , BUT, this 2 that is going to be removed will be the first and not the last:

remove(2)

  

Remove the first item from the list whose value is x.

Translation

  

Removes the first item from the list whose value is x.

DOCS

That is what will happen to your list during your second loop remove(x) is:

  

[2, 5, 2, 0]
[2, 5, 2]
[2, 5]
[5, 2]
[5]

And the while prints that in this case will be:

  

2 of 2
2 of 5

(do not forget that 0 was deleted before the first print)

If you allow me to present a suggestion for improvement (to do just this) without modifying your code very 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 delete it at the 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 go even further, if the objective is just to print and remove the inputs that are in the list in reverse order we can eliminate 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()
    
28.02.2017 / 23:55