Python reversed()

The reversed() function returns the reversed iterator of the given sequence.

The syntax of reversed() is:


reversed() Parameters

The reversed() function takes a single parameter:

  • seq - the sequence to be reversed

A sequence is an object that supports sequence protocols: __len__() and __getitem__() methods. For example, tuple, string, list, range, etc.

We can also use reversed() in any object that implements __reverse__().

Return value from reversed()

The reversed() function returns an iterator that accesses the given sequence in the reverse order.

Example 1: Using reveresed() in string, tuple, list, and range

# for string
seq_string = 'Python'

# for tuple
seq_tuple = ('P', 'y', 't', 'h', 'o', 'n')

# for range
seq_range = range(5, 9)

# for list
seq_list = [1, 2, 4, 3, 5]


['n', 'o', 'h', 't', 'y', 'P']
['n', 'o', 'h', 't', 'y', 'P']
[8, 7, 6, 5]
[5, 3, 4, 2, 1]

In our example, we have converted the iterators returned by reversed() to list using the list() function.

Example 2: reversed() in custom objects

class Vowels:
    vowels = ['a', 'e', 'i', 'o', 'u']

    def __reversed__(self):
        return reversed(self.vowels)

v = Vowels()


['u', 'o', 'i', 'e', 'a']
Did you find this article helpful?