Python reversed()

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

The syntax of reversed() is:

reversed(seq)

reversed() Parameters

The reversed() method takes a single parameter:

  • seq - sequence that should be reversed
    Could be an object that supports sequence protocol (__len__() and __getitem__() methods) as tuple, string, list or range
    Could be an object that has implemented __reversed__()

Return value from reversed()

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


Example 1: How reversed works for a sequence: string, tuple, list and range?

# for string
seqString = 'Python'
print(list(reversed(seqString)))

# for tuple
seqTuple = ('P', 'y', 't', 'h', 'o', 'n')
print(list(reversed(seqTuple)))

# for range
seqRange = range(5, 9)
print(list(reversed(seqRange)))

# for list
seqList = [1, 2, 4, 3, 5]
print(list(reversed(seqList)))

When you run the program, the output will be:

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

Example 2: How reversed works for custom objects by implementing __reversed__()?

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

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

v = Vowels()
print(list(reversed(v)))

When you run the program, the output will be:

['u', 'o', 'i', 'e', 'a']