Tutorial Study Image

Python reversed()

The built-in function reversed()  accepts a sequence as its input and returns an iterator, the iterator should be in a reversed order of a given sequence. We can also use reversed() in any object that implements __reverse__().


reversed(seq) #where seq can be tuple,string,list,range, etc.
 

reversed() Parameters:

Takes single parameter. If we pass objects which do not maintain their orders like dict and set, then it will result in a TypeError.

Parameter Description Required / Optional
seq The sequence to be reversed Required

reversed() Return Value

If we want to get the reverse of user-defined objects the class must do any one of the following:

To implement __len__()  and __getitem__()  methods
Or to implement __reversed__() method

Input Return Value
 seq(list,string etc) reversed sequence

Examples of reversed() method in Python

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


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

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

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

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

Output:

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

Example 2: reversed() in custom objects


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

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

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

Output:

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