Special Method Protocols

__reversed__() — containers protocol

Return a reverse iterator for reversed(obj). If absent, reversed can use the sequence protocol (__len__ and integer __getitem__). Do not mutate the receiver merely to traverse it backwards.

Formal Syntax & Structure

python syntaxpython
def __reversed__(self):

Return Value

iterator

Reverse traversal iterator.

Working Example

Example Snippetpython
class Bag:    def __init__(self): self.items=[1,2,3]    def __reversed__(self): return reversed(self.items)print(list(reversed(Bag())))
Python Reference