Calling `reverse 'on a list against another iterator (like a tuple) results in different output

Call reversed

in the list:

>>> reversed([1, 2, 3])
<list_reverseiterator object at 0x102a84908>

      

Now call it another iterable ... let's say a tuple:

>>> reversed((1, 2, 3))
<reversed object at 0x102a848d0>

      

The first bit of code gives a list_reverseiterator object

and the second gives reversed object

.

Similar behavior is observed in all pythons. So why is there a difference?

In documents

Return a reverse iterator. seq must be an object that has __reversed__()

or supports a sequencing protocol (method __len__()

and method __getitem__()

with integer arguments starting at 0).

Is it related to whether it is being implemented __reversed__

or not? Because...

>>> list.__reversed__
<method '__reversed__' of 'list' objects>

      

But

>>> tuple.__reversed__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'tuple' has no attribute '__reversed__'

      

+3


source to share





All Articles