Reverse traversal
Process sequence elements from newest or last to first without changing the source.
Python · Function
Returns an iterator that traverses a supported object in reverse order. It does not itself create or mutate a reversed collection.
reversed() creates a reverse iterator for a suitable object. The object must provide __reversed__(), or support the sequence protocol through __len__() and integer-indexed __getitem__().
reversed(object, /)| Name | Type | Description |
|---|---|---|
object | object | Object to traverse backward; it must implement __reversed__() or the required sequence protocol. |
A reverse iterator.
numbers = [1, 2, 3]
for number in reversed(numbers):
print(number)Iterates over the list from its last element to its first without changing the original list.
Process sequence elements from newest or last to first without changing the source.
Feed backward iteration into a loop or another iterator-consuming operation.
Provide custom reverse behavior for a container by implementing __reversed__().
reversed() returns an iterator rather than a reversed copy. It works when the input defines __reversed__(), or when it supports __len__() and integer-based __getitem__() starting at zero.
Follow-up: How can a custom container control reverse iteration? Define __reversed__() and return a new iterator that yields the container's elements in reverse order.
The function uses a custom __reversed__() method when one exists. Otherwise, it can use the sequence protocol, requiring __len__() and integer-indexed __getitem__() beginning with index 0.
Follow-up: What should __reversed__() return? A new iterator that traverses all container objects in reverse order.
The returned iterator produces elements from the end toward the beginning, while the original sequence remains unchanged. Converting the iterator to list is optional when a materialized result is required.
Follow-up: When is list(reversed(value)) appropriate? Use it when repeated access, indexing, or a persistent reversed collection is needed.
__reversed__()__len__()__getitem__()iter()list()sorted()