reversed(seq)
Returns a reverse iterator over the specified sequence seq. The sequence must have a __reversed__() method or both a __len__ and a __getitem__ method with integers starting from 0.
Parameters
The reversed() function takes one parameter:
sequence_object— an indexable object to reverse (can be a tuple, string, list, range, etc.)
Note: Since sets and dictionaries cannot be indexed, they are not considered sequence objects.
Return Value
The reversed() function returns:
- a reversed iterator of elements in the sequence object
Examples
seq_tuple = ('C', 'A', 'T', 'S')
# Reverse the tuple object
print(list(reversed(seq_tuple)))
seq_range = range(3, 7)
# Reverse the range
print(list(reversed(seq_range)))
seq_list = [1, 2, 4, 3, 5]
# Reverse the list
print(list(reversed(seq_list)))
# Output
['S', 'T', 'A', 'C']
[6, 5, 4, 3]
[5, 3, 4, 2, 1]