Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Reverse a Custom Sequence with __reversed__

Implement __reversed__ so the built-in reversed() returns elements in reverse order for your custom sequence.

Python practice28 minMagic Methods & Operator OverloadingAdvancedLast updated April 11, 2026

Problem statement

You have a ReversibleSequence class that wraps an ordered collection of items and already implements __len__ and __getitem__ so it behaves like a sequence. Implement the __reversed__ magic method to return an iterator that yields the elements of the sequence in reverse order. The reversed() builtin should use your __reversed__ implementation. Your method should not create an unnecessary copy of the underlying list; use an iterator/generator.

Task

Provide a __reversed__ implementation that returns an iterator over the sequence elements in reverse order, allowing reversed(instance) to work efficiently.

Examples

Reverse a list of ints

Input

list(reversed(ReversibleSequence([1, 2, 3, 4])))

Output

[4, 3, 2, 1]

reversed(...) yields elements from last to first: 4,3,2,1.

Input format

Construct ReversibleSequence(items) and pass it to reversed() or iterate over reversed(sequence).

Output format

An iterator over the sequence elements in reverse order (can be consumed by list(), join(), for-loops, etc.).

Constraints

Do not modify __len__ or __getitem__. Implement __reversed__ to return an iterator/generator; avoid copying the entire list into a new list just to reverse it.

Samples

Sample 1

Input

''.join(reversed(ReversibleSequence('hello')))

Output

olleh

Characters are yielded in reverse order, forming the reversed string.