Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing list in reverse order not working - Python 3x

Tags:

python

list

I'm writing a program that keeps asking the user to enter names until the word END is entered, at which point it prints out the list of names in reverse order.

At first, I didn't know how to print out a list in reverse order, so I found this: Traverse a list in reverse order in Python

I decided to use the reversed() built-in function:

import getpass
import time
import sys
print("Welcome " + getpass.getuser() + "...")
time.sleep(0.25)
print("This program, powered by Python, it will ask you to enter names...")
time.sleep(0.5)
print("...once you have finished, enter END to print off your list")
names = []
while True:
    name = input("Please enter a name: ")
    if name == "END":
        print(reversed(names))
        sys.exit()
    names.append(name)

However, all it prints is:

<list_reverseiterator object at 0x0000000002A14F28>

Why is this happening and how can I tackle this issue?

Many thanks

like image 761
Turbo Avatar asked Apr 10 '26 09:04

Turbo


2 Answers

reversed returns an iterator that will iterate the list in a reversed order. It will not return a reversed list. This is an important difference because if it returned a reversed list, then that list would have to be allocated in memory. So you would end up with a copy of it; and you would have to iterate over it twice (once for creating the reversed list, and then once for printing it).

Instead reversed just begins iterating at the end of the original list. You can easily see this if you modify the list after creating the reversed iterator:

>>> a = [1,2,3,4,5]
>>> r = reversed(a)
>>> a[2:2] = [10, 11, 12, 13]
>>> a
[1, 2, 10, 11, 12, 13, 3, 4, 5]
>>> list(r)
[12, 11, 10, 2, 1]

The reversed iterator just remembered the index where it would start iterating (i.e. index 4). With the modified list, this no longer is the end of the list though.

So, if you want to have a copied list in reversed order, you will have to call list on it, to create one from it. Otherwise, if you can, you should really just try to iterate on the reversed iterator.

like image 101
poke Avatar answered Apr 12 '26 22:04

poke


For the sake of efficiency, reversed returns an iterator object instead of a full list. This way, it doesn't have to allocate any additional space, or do much work at all, until the user starts iterating through it.

As pointed out by behzad, the easiest way to get your results in list form is to use list.

>>> seq = [1,2,3]
>>> x = reversed(seq)
>>> print list(x)
[3, 2, 1]
like image 42
Kevin Avatar answered Apr 12 '26 22:04

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!