Use the reversed function
#the iterable containing the elements to reverse
iterable = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
reversed_elements = reversed(iterable)
print(tuple(reversed_elements))
The reversed()
function returns a reverse iterator of the input iterable. It allows us to reverse the elements of an iterable object (list, string, tuple, etc.) without modifying the original iterable.
Syntax:
reversed(iterable)
The required iterable
parameter specifies the iterable object whose elements are to be reversed (e.g. a list, string, or tuple, etc). The iterable object should have the __reversed__()
method implemented .
The function returns an iterator objects containing the elements of the input iterable in reverse. We can then cast the returned iterator object into the relevant sequence type.
Reverse list items
Reverse items in a list
L = ['a', 'b', 'c', 'd', 'e', 'f']
reversed_L = reversed(L)
print(list(reversed_L))
L = ['Ruby', 'Java', 'Python', "C++", "PHP"]
reversed_L = reversed(L)
print(list(reversed_L))
Reverse tuple items
Reverse items in a tuple
T = ('Python', 'Java', 'Ruby')
reversed_T = reversed(T)
print(tuple(reversed_T))
Reverse a string
Reversing a string
S = "Hello, World!"
reversed_S = reversed(S)
print("".join(reversed_S))
In the above example we used the join()
method to join the reversed iterator back to a string.
Reverse a range
Reverse range items
R = range(10)
reversed_R = reversed(R)
for i in reversed_R:
print(i)