reversed()
The built-in reversed()
function takes a sequence as an argument and returns an iterator that yields the elements in reverse order. The function does not modify the original iterable:
>>> list(reversed([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
reversed()
Signature
reversed(seq)
Arguments
Argument | Description |
---|---|
seq |
A sequence or reversible object to be reversed. |
Return Value
- An iterator that yields the elements of the input iterable in reverse order.
reversed()
Examples
With tuples and lists as an argument:
>>> tuple(reversed((1, 2, 3, 4)))
(4, 3, 2, 1)
>>> list(reversed(["a", "b", "c", "d"]))
['d', 'c', 'b', 'a']
With a string as an argument:
>>> "".join(reversed("Hello, World!"))
'!dlroW ,olleH'
reversed()
Common Use Cases
The most common use cases for the reversed()
function include:
- Iterating over a sequence in reverse order without modifying the original data.
- Reversing lists of strings for display or processing.
- Creating a reversed copy of a sequence.
reversed()
Real-World Example
Suppose you have a list of tasks that need to be processed in reverse order. You can use the reversed()
function to iterate over the list from last to first:
>>> tasks = ["task1", "task2", "task3", "task4"]
>>> for task in reversed(tasks):
... print("Processing", task)
...
Processing task4
Processing task3
Processing task2
Processing task1
In this example, reversed()
allows you to efficiently process tasks in reverse order without altering the original list.
reversed()
in Custom Classes
The .__reversed__()
special method allows you to support reversed()
in your custom classes. It must return an iterator over the items of the current list in reverse order. For example, say you want to iterate over a range of floating-point numbers. You end up with a class like this:
float_range.py
class FloatRange:
def __init__(self, start, stop, step=1.0):
if start >= stop:
raise ValueError("Invalid range")
self.start = start
self.stop = stop
self.step = step
def __iter__(self):
n = self.start
while n < self.stop:
yield n
n += self.step
def __reversed__(self):
n = self.stop - self.step
while n >= self.start:
yield n
n -= self.step
# Usage
for number in FloatRange(0.0, 2.0, 0.5):
print(number) # Output: 0.0 0.5 1.0 1.5
for number in reversed(FloatRange(0.0, 2.0, 0.5)):
print(number) # Output: 1.5 1.0 0.5 0.0
This class allows you to iterate through an interval of floating-point numbers using a fixed increment value, step
. In your class, .__iter__()
provides support for normal iteration, and .__reversed__()
supports reverse iteration.
Related Resources
Tutorial
Reverse Python Lists: Beyond .reverse() and reversed()
In this step-by-step tutorial, you'll learn about Python's tools and techniques to work with lists in reverse order. You'll also learn how to reverse your list by hand.
For additional information on related topics, take a look at the following resources:
- Iterators and Iterables in Python: Run Efficient Iterations (Tutorial)
- How to Use Generators and yield in Python (Tutorial)
- Python Generators 101 (Course)
- Python range(): Represent Numerical Ranges (Tutorial)
- Efficient Iterations With Python Iterators and Iterables (Course)
- Iterators and Iterables in Python: Run Efficient Iterations (Quiz)
- How to Use Generators and yield in Python (Quiz)
- The Python range() Function (Course)