Python reversed() function returns an iterator that grants access to the elements of a sequence in reverse order.
It works with any object that supports sequence protocol, such as tuple, string, list, and other sequence-like objects.
Keep in mind that reversed() does not work with sets or dictionaries, as they are not sequences.
Syntax
reversed(sequence)
Parameters
sequence(required): It can be any sequence-like object.
Return value
Returns a reversed list of elements in a sequence object.
Example 1: Using with list
watches_list = ["Rolex", "Patek Philippe", "OMEGA"]
print("Original List:",watches_list)
reversed_list = list(reversed(watches_list))
print("Reversed List:",reversed_list)
Output
Original List: ['Rolex', 'Patek Philippe', 'OMEGA']
Reversed List: ['OMEGA', 'Patek Philippe', 'Rolex']
Example 2: Using with tuple
new_tuple = ('A', 'B', 'C', 'D')
print("Original Tuple:",new_tuple)
reversed_list = list(reversed(new_tuple))
print("Reversed Tuple:",reversed_list)
Output
Original Tuple: ('A', 'B', 'C', 'D')
Reversed Tuple: ['D', 'C', 'B', 'A']
Example 3: Using with string
new_string = "Taylor"
print("Original String:",new_string)
reversed_list = list(reversed(new_string))
print("Reversed String:",reversed_list)
Output
Original String: Taylor
Reversed String: ['r', 'o', 'l', 'y', 'a', 'T']
Example 4: Using with Custom Objects
class Primes:
def __init__(self, *primes):
self.primes = primes
def __reversed__(self):
return reversed(self.primes)
# Instantiate the class with some prime numbers
prime_obj = Primes(2, 3, 5, 7, 11, 13, 17)
# Reverse the prime numbers in the object
reversed_primes = list(reversed(prime_obj))
print(reversed_primes)
Output
[17, 13, 11, 7, 5, 3, 2]