ZetCode

Python __reversed__ Method

Last modified November 18, 2026 Python 3.15

The built-in reversed() function calls __reversed__ on its argument. Without that hook it falls back to the sequence protocol, using __len__ and __getitem__. A custom hook is useful when reverse traversal has a cheaper or more natural implementation than walking forward indices. This article demonstrates the fallback, a dedicated reverse iterator, generator-based hooks, a linked list, slice-based reversal and reverse tree traversal.

The sequence fallback

A class with __len__ and __getitem__ can be reversed even without __reversed__. Python walks the indices from the last one down to zero.

fallback.py
class Sequence:
    def __init__(self, data):
        self.data = list(data)

    def __len__(self):
        return len(self.data)

    def __getitem__(self, index):
        return self.data[index]


seq = Sequence([1, 2, 3, 4, 5])
print(list(reversed(seq)))

The fallback works automatically. It also means reversed() requires those two methods: an object that only implements __iter__ is reported as not reversible.

$ python fallback.py
[5, 4, 3, 2, 1]

An explicit __reversed__

Defining the hook lets the class choose its own algorithm. Here it prints a message, then delegates to the built-in reversed() of the stored list.

explicit.py
class Sequence:
    def __init__(self, data):
        self.data = list(data)

    def __len__(self):
        return len(self.data)

    def __getitem__(self, index):
        return self.data[index]

    def __reversed__(self):
        print("__reversed__ called")
        return reversed(self.data)


print(list(reversed(Sequence([1, 2, 3]))))

The message confirms that Python preferred __reversed__ over the sequence fallback. The hook must return an iterator, which reversed(self.data) already is.

$ python explicit.py
__reversed__ called
[3, 2, 1]

A custom reverse iterator

A dedicated iterator can keep its own index and count down. It implements __iter__ and __next__, raising StopIteration when the index reaches zero.

custom_iterator.py
class ReverseIterator:
    def __init__(self, sequence):
        self.sequence = sequence
        self.index = len(sequence)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index -= 1
        return self.sequence[self.index]


class Sequence:
    def __init__(self, data):
        self.data = list(data)

    def __len__(self):
        return len(self.data)

    def __getitem__(self, index):
        return self.data[index]

    def __reversed__(self):
        return ReverseIterator(self)


print(list(reversed(Sequence([10, 20, 30, 40]))))

The iterator starts at the length and decrements before each access, so it yields the last element first. This pattern also works when elements are computed rather than stored.

$ python custom_iterator.py
[40, 30, 20, 10]

A generator as the hook

Because a generator is an iterator, __reversed__ can simply be a generator function. This is the shortest way to implement custom reverse order.

generator.py
class Countdown:
    def __reversed__(self):
        for value in range(3, 0, -1):
            yield value


cd = Countdown()
print(list(reversed(cd)))
print(list(reversed(cd)))

Each call to reversed() creates a fresh generator, so the sequence can be reversed repeatedly. Storing a generator on the instance instead would make it single-use.

$ python generator.py
[3, 2, 1]
[3, 2, 1]

Reversing a linked list

A singly linked list has no cheap backwards links. The hook can materialize the values and reverse them, which is simple and correct for modest lists.

linked_list.py
class Node:
    def __init__(self, value, next_node=None):
        self.value = value
        self.next = next_node


class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, value):
        if self.head is None:
            self.head = Node(value)
            return
        current = self.head
        while current.next:
            current = current.next
        current.next = Node(value)

    def __iter__(self):
        current = self.head
        while current:
            yield current.value
            current = current.next

    def __reversed__(self):
        return reversed(list(self))


lst = LinkedList()
for value in (1, 2, 3):
    lst.append(value)
print(list(lst))
print(list(reversed(lst)))

Forward iteration yields the values in insertion order; reversed iteration yields them backwards. For a very large list, a dedicated iterator that traverses once from the tail would avoid the temporary list.

$ python linked_list.py
[1, 2, 3]
[3, 2, 1]

Reversing with slice syntax

A class that supports slicing can return a reverse view with [::-1]. The result is an iterator-producing sequence, so reversed() accepts it.

slice.py
class Sliceable:
    def __init__(self, data):
        self.data = list(data)

    def __len__(self):
        return len(self.data)

    def __getitem__(self, index):
        return self.data[index]

    def __reversed__(self):
        return iter(self.data[::-1])


s = Sliceable([1, 2, 3, 4])
print(list(reversed(s)))

The slice produces a new list in reverse order and iter() turns it into the iterator the built-in expects. Applying reversed() a second time here would undo the slice, so only iter() is needed. For a huge sequence, an index-counting iterator avoids copying the data.

$ python slice.py
[4, 3, 2, 1]

Reverse tree traversal

A tree can define what "reverse" means for its structure. Here a nested generator visits children in reverse order and yields each node after its descendants, giving a reverse post-order walk.

tree.py
class TreeNode:
    def __init__(self, value):
        self.value = value
        self.children = []

    def add_child(self, node):
        self.children.append(node)

    def __repr__(self):
        return f"Node({self.value})"


class Tree:
    def __init__(self, root):
        self.root = root

    def __reversed__(self):
        def traverse(node):
            for child in reversed(node.children):
                yield from traverse(child)
            yield node.value
        return traverse(self.root)


root = TreeNode(1)
left = TreeNode(2)
right = TreeNode(3)
root.add_child(left)
root.add_child(right)
left.add_child(TreeNode(4))
left.add_child(TreeNode(5))

print(list(reversed(Tree(root))))

The right subtree comes first, then the left subtree's children in reverse, then their parent, and finally the root. The old version of this example had an extra closing parenthesis and could not run.

$ python tree.py
[3, 5, 4, 2, 1]

Best practices

A few rules keep __reversed__ predictable:

Source

reversed() - Python documentation

object.__reversed__ - Python documentation

Iterator types - Python documentation

In this article we have implemented the __reversed__ method. We have covered the sequence fallback, explicit hooks, custom iterators, generators, linked lists, slices and reverse tree traversal. For related topics, see Python __iter__ method, Python __next__ method, and Python itertools.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.