The reversed(seq) function returns a reverse iterator over the elements of a sequence without duplicating the underlying data.
Memory-Efficient Traversal: Unlike string or list slicing (seq[::-1]) which copies the entire collection into memory, reversed() operates in O(1) auxiliary space by stepping backward through the existing sequence. It natively supports lists, tuples, ranges, and strings, as well as custom classes implementing the __reversed__() dunder method. To transform sequences lazily from left to right, see map() and filter().
The reversed() function accepts a sequence object and returns an iterator:
rev_iter = reversed(sequence)
| Parameter | Type Accepted | Behavioral Details |
|---|---|---|
sequence |
Sequence or reversible object | Must implement __reversed__(), OR support __len__() and __getitem__() starting at 0. |
| Return Value | Reverse iterator | Returns a reverse iterator (such as list_reverseiterator or reversed object). |
You can traverse lists and tuples backward without mutating the original collection:
# 1. Reversing a list
words = ["One", "Two", "Three"]
rev_words = reversed(words)
print("Reversed list:", list(rev_words))
print("Original list untouched:", words)
# 2. Reversing an immutable tuple
numbers = (10, 20, 30)
rev_numbers = tuple(reversed(numbers))
print("Reversed tuple:", rev_numbers)
Output:
Reversed list: ['Three', 'Two', 'One']
Original list untouched: ['One', 'Two', 'Three']
Reversed tuple: (30, 20, 10)
Because strings and ranges conform to the sequence protocol, they can be reversed directly:
# 1. Reversing a range
count_down = reversed(range(6))
print("Reversed range:", list(count_down))
# 2. Reversing a string and rejoining
site_name = "plus2net"
reversed_str = "".join(reversed(site_name))
print("Reversed string:", reversed_str)
# 3. Using reversed with enumerate()
letters = ["a", "b", "c", "d"]
for idx, val in enumerate(reversed(letters)):
print(f"Index {idx}: {val}")
Output:
Reversed range: [5, 4, 3, 2, 1, 0]
Reversed string: ten2sulp
Index 0: d
Index 1: c
Index 2: b
Index 3: a
reversed() vs. Slice Step [::-1] 🔝Both methods traverse sequences backward, but have major memory and performance trade-offs:
| Criterion | reversed(seq) |
Slicing seq[::-1] |
|---|---|---|
| Evaluation Timing | Lazy iterator (steps backward on-demand) | Eager (allocates entire reversed copy) |
| Memory Footprint | O(1) constant auxiliary memory | O(N) memory for the new copy |
| Return Type | Iterator | Same sequence type (list, tuple, str) |
| Suitability | Large loops, streams, and generators | When an immediate copy is required |
reversed() vs. list.reverse() 🔝Compare non-destructive iteration with in-place list mutation:
data_a = [1, 2, 3]
data_b = [1, 2, 3]
# 1. list.reverse() mutates in-place and returns None
ret = data_a.reverse()
print("data_a mutated in-place:", data_a, "Return:", ret)
# 2. reversed() yields iterator, leaves source unchanged
rev_it = reversed(data_b)
print("data_b original intact:", data_b)
print("rev_it consumed: ", list(rev_it))
Output:
data_a mutated in-place: [3, 2, 1] Return: None
data_b original intact: [1, 2, 3]
rev_it consumed: [3, 2, 1]
__reversed__() 🔝You can make any custom class reversible by implementing the __reversed__() dunder method:
class Countdown:
def __init__(self, start: int):
self.start = start
def __reversed__(self):
curr = self.start
while curr >= 0:
yield curr
curr -= 1
timer = Countdown(4)
print("Custom countdown:", list(reversed(timer)))
Output:
Custom countdown: [4, 3, 2, 1, 0]
Validate if a word is a palindrome in constant space using reversed() and zip():
def is_palindrome(text: str) -> bool:
clean = text.lower()
return all(a == b for a, b in zip(clean, reversed(clean)))
print("radar palindrome:", is_palindrome("radar"))
print("python palindrome:", is_palindrome("python"))
Output:
radar palindrome: True
python palindrome: False
Scan audit records backward to find the most recent event matching a condition without copying the log:
audit_logs = [
{"id": 1, "status": "ok"},
{"id": 2, "status": "failed"},
{"id": 3, "status": "ok"}
]
def find_latest_failure(logs: list[dict]):
for entry in reversed(logs):
if entry["status"] == "failed":
return entry
return None
print("Latest failure:", find_latest_failure(audit_logs))
Output:
Latest failure: {'id': 2, 'status': 'failed'}
reversed() on an unordered collection like a set or dict raises a TypeError: 'set' object is not reversible. Convert to a list or sorted sequence first.
my_set = {1, 2, 3}
try:
reversed(my_set)
except TypeError as err:
print("Set reversal error:", err)
# Correct: convert to list first
print("Safe sorted reversal:", list(reversed(sorted(my_set))))
Output:
Set reversal error: 'set' object is not reversible
Safe sorted reversal: [3, 2, 1]
Practice reverse sequence traversal, custom iterators, and log scanning in our companion Jupyter Notebook:
Explore interactive code cells, compare memory allocations between reversed() and slicing, build custom __reversed__ generators, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify reversed() mechanics:
def test_reversed_mechanics():
assert list(reversed([1, 2, 3])) == [3, 2, 1]
assert tuple(reversed(("a", "b"))) == ("b", "a")
assert "".join(reversed("noon")) == "noon"
assert list(reversed(range(3))) == [2, 1, 0]
try:
reversed({1, 2})
assert False
except TypeError:
pass
print("All reversed() unit assertions passed! 100% verified.")
test_reversed_mechanics()
Output:
All reversed() unit assertions passed! 100% verified.
Applies a function to all elements in an iterable, returning a lazy transformation iterator.
Filters elements from an iterable based on whether a function evaluates to True.
Generates and advances forward through iterator sequences.
Comprehensive guide on reversing strings using slicing, reversed(), and loops.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.