In Python, the reversed() function returns a reverse iterator used to reverse the elements in a sequence (e.g., list, tuple, string, etc.).

Function Syntax

reversed(seq)

Parameter:

  • seq: The sequence to be reversed. It can be any object that implements the __reversed__() method, or any object that implements both the __len__() and __getitem__() methods.

The reversed() function returns a reverse iterator object.

Internal Implementation

  1. First attempts to call the __reversed__() method. If it exists, returns the result.
  2. If there is no __reversed__() method, checks for the presence of __len__() and __getitem__() methods. If both exist, constructs and returns a new reverse iterator.
  3. If none of the above methods are available, raises a TypeError exception.

Usage Examples

Basic usage:

my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))
print(reversed_list)  # [5, 4, 3, 2, 1]

my_string = "hello"
reversed_string = ''.join(reversed(my_string))
print(reversed_string)  # olleh

Non-reversible objects (those not implementing the required special methods) are not supported:

a = 3.14
# reversed(a) # TypeError: 'float' object is not reversible
print(hasattr(a,'__reversed__')) # False
print(hasattr(a,'__len__')) # False

Custom __reversed__() method:

class CountDown:
    def __init__(self, start):
        self.start = start
    
    def __iter__(self):
        n = self.start
        while n > 0:
            yield n
            n -= 1
    
    def __reversed__(self):
        n = 1
        while n <= self.start:
            yield n
            n += 1

cd = CountDown(5)
print("Forward:", list(cd))  # [5, 4, 3, 2, 1]
print("Reversed:", list(reversed(cd)))  # [1, 2, 3, 4, 5]