How to print list elements in reverse order?

Asked

Viewed 1,958 times

2

I created a program that takes integers from the user and prints them back in the reverse order that received them, however my program is not returning all integers it receives. When I enter 9 integers for example, it only prints 5.

    i = int(input('Digite um número: '))
lista = []

while i > 0:
    lista.append(i)
    i = int(input('Digite um número: '))

for i in lista:
    print(lista[-1])
    del(lista[-1])

Exemplo

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site

3 answers

4

If you can use something ready have at least two techniques:

lista = []
while True:
    i = int(input('Digite um número: '))
    if i < 1: break
    lista.append(i)
for i in lista[::-1]:
    print(i)
for i in reversed(lista):
    print(i)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Both generate an iterator for the list in the inverted order. The first uses the Slice to indicate that it starts from beginning to end as no starting and ending position has been placed before the two signs of : and in the end it puts of how much on how much it should walk, therefore it shows that it should go in negative position, so it indicates that it should go decreasing each position.

Never change the composition of a complex object as a list during the loop, mainly by deleting items, this will almost always go wrong because the iterator was prepared for something that no longer exists. You can change the internal data but not the list as it was done.

In addition the problem asks to print reversed and not keep erasing the data.

I modified the loop because I think it’s wrong to ask for the die in and out of the loop (see DRY). In a simple example may not cause problems, but get used wrong. There I solved some other problems that happened in the code, but it is not the focus of the question.

I did not consider that typing can be wrong and break the application, the correct is to treat it by capturing exception, or creating a proper function that better handles it.

If the problem prevented using any of the language’s own resources then it would have to iterate each item starting from the last one to the first one, having a counter to control it, but in real codes this restriction does not make sense.

1

It turns out that in:

for i in lista:
    print(lista[-1])
    del(lista[-1])

At each iteration, the last value in the list is deleted, for example, the list will be at the end of all your inserts: [9, 8, 7, 6, 5, 4, 3, 2, 1].

In the for, when iterating 9, 1 will be deleted, when iterating 8, 2 will be deleted, and so on. When it reaches 5, this will be the last value to be iterated.

  • 2

    If you’re doing del(lista[-1]), why would the first element be excluded? The answer makes no sense.

  • 1

    So, young man, it turns out the '-1' and the reverse reading position of the list, del(lista[-1[) is the same as performing a.pop() list, which results in the item being removed. If you insist, just make a stop at each iteration and you will see that is exactly what is happening.

  • 1

    Maniero’s answer does exactly what St3h wants to do, what I did was to clarify why his test is resulting in something that is not expected.

  • 1

    But the explanation is wrong. At no time are the first values removed. Displays 9 and removes it from the list; displays 8 and removes it from the list... the problem is iterating the list and changing it at the same time.

  • 1

    In doing i in lista, i will be valid 1 and will be displayed 9, removing it; then i valley 2 and displays the 8, removing it; then i valley 3 displaying the 7, removing it; then i worth 4 displaying the 6, removing it; then i valley 5, displaying the 5, removing it. As the values 6, 7, 8 and 9 have been removed, the loop is closed.

  • 1

    The question is the reverse reading.

Show 1 more comment

0

To resolve this issue we must assemble 2 repeat loops. One to assemble the list and one to read and display the list values in reverse order.

Well, to resolve this issue we can use the following code:

i = int(input('Digite um número: '))
lista = list()
while len(lista) < i:
    lista.append(int(input(f'Digite {len(lista) + 1}º número: ')))

while len(lista) >= 1:
    print(f'O {len(lista)}º elemento da lista é: {lista[-1]}')
    del(lista[-1])

See here the functioning of the code.

Note that when we execute the code we must enter the amount of elements in the list. Later, we must enter each of the n values and pressure enter.

Then the list elements are displayed in inverse insertion order.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.