In discussion of this answer we realized that tuples do not have a __reversed__
method. My guess was that creating the iterator would require mutating the tuple. And yet tuples play fine with reversed
. Why can't the approach used for reversed
be made to work for __reversed__
as well?
>>> foo = range(3)
>>> foo
[0, 1, 2]
>>> list(foo.__reversed__())
[2, 1, 0]
>>> foo
[0, 1, 2]
>>> bar = (0, 1, 2)
>>> list(bar.__reversed__())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute '__reversed__'
>>> reversed(bar)
<reversed object at 0x10603b310>
>>> tuple(reversed(bar))
(2, 1, 0)
According to the spec:
reversed(seq)
Return a reverse iterator. seq must be an object which has a reversed() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With