Reversing Sequences in Python: Efficient Traversal with reversed()

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().

1. Syntax & Formal Parameter Specifications 🔝

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).

2. Basic Usage: Reversing Lists & Tuples 🔝

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)

3. Reversing Strings and Ranges 🔝

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

4. 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

5. 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]

6. Custom Class Reversal with __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]

7. Production Recipes & Real-World Use Cases 🔝

Recipe A: Efficient Palindrome Verification

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

Recipe B: Most Recent Transaction / Log Scanner

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'}

8. Common Pitfalls & Developer Traps 🔝

The Unordered Collection Trap: Calling 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]

9. Interactive Notebook & Practice Exercises 🔝

Practice reverse sequence traversal, custom iterators, and log scanning in our companion Jupyter Notebook:

Interactive 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 Colab

Self-Verifying Assertion Suite

Run 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.
map()

Applies a function to all elements in an iterable, returning a lazy transformation iterator.

filter()

Filters elements from an iterable based on whether a function evaluates to True.

iter() / next()

Generates and advances forward through iterator sequences.

String Reversal

Comprehensive guide on reversing strings using slicing, reversed(), and loops.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer