Python reversed() function

Python reversed() function returns a reversed iterator from the specified sequence argument.

Python reversed()

Python reversed() function syntax is:

  • The input argument must be a sequence, for example tuple, list, string etc.
  • The returned object is of type reversed and it’s an iterator.
  • We can supply a custom object as reversed() function argument if it has __reversed__() method or supports the sequence protocol.
  • We need to implement __len__() method and the __getitem__() method with integer arguments starting at 0 to support sequence protocol.

reversed() with sequence

Let’s look at reversed() function examples with standard sequence objects such as string, bytes, tuple, list etc.

def print_iterator(it):
    for x in it:
        print(x, end=' ')
# reversed string
r = reversed('abc')
# reversed list
r = reversed([1, 2, 3])
# reversed tuple
r = reversed((1, 2, 3))
# reversed bytes
r = reversed(bytes('abc', 'utf-8'))
# reversed bytearray
r = reversed(bytearray('abc', 'utf-8'))


<class 'reversed'>
<reversed object at 0x109d1f208>
c b a
3 2 1
3 2 1
99 98 97
99 98 97

Notice that bytes and bytearray elements are converted to integer while printing on console.

reversed() with object having __reversed__ method

# object with __reversed__ method
class Data:
    def __init__(self, n): = n
    def __reversed__(self):
        return reversed(
d = Data('ABC')
r = reversed(d)

Output: C B A

reversed() with object supporting sequence protocol

# object supporting sequence protocol i.e.
# implementing __len__() and __getitem__ method
class MyTupleWrapper:
    t = ()
    def __init__(self, tu):
        if not isinstance(tu, tuple):
            return ValueError('Only accepts tuple')
        self.t = tu
    def __len__(self):
        return len(self.t)
    def __getitem__(self, index):
        return self.t[index]
mt = MyTupleWrapper((1, 2, 3, 4))
r = reversed(mt)

Output: 4 3 2 1

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: