3

I am trying to use the reversed function on a list and I am having trouble with the return value.

s=[0,1,2,3]
print(reversed(s))

This returns this line: <list_reverseiterator object at 0x000001488B6559A0>

I know the reversed() function returns an iterator object. Can someone elaborate more on 'iterator object'?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
HappyShifu
  • 33
  • 4
  • Does this answer your question? [What exactly are iterator, iterable, and iteration?](https://stackoverflow.com/questions/9884132/what-exactly-are-iterator-iterable-and-iteration) – Gino Mempin Aug 22 '21 at 05:32

2 Answers2

4

An iterator object is a object is virtually the same thing as generators.

From the docs:

Generators are iterators, but you can only iterate over them once. It’s because they do not store all the values in memory, they generate the values on the fly. You use them by iterating over them, either with a ‘for’ loop or by passing them to any function or construct that iterates. Most of the time generators are implemented as functions. However, they do not return a value, they yield it.

The way to fix this would be:

print(list(reversed(s)))

Output:

[3, 2, 1, 0]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

You know that by using this reversed function you will be iteration the list in reverse order. do this

s=[0,1,2,3]
reversed_s = reversed(s)
for item in reversed_s:
    print(item)
David Arias
  • 182
  • 14