What is an 'iterator object' as returned by the reversed function?

Viewed 165

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'?

2 Answers

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]

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)
Related