ExampleEdit & Run

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))
Output:
(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)[Finished in 0.010556031949818134s]

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 .

Parameters:

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

ExampleEdit & Run

Reverse items in a list

L = ['a', 'b', 'c', 'd', 'e', 'f']

reversed_L = reversed(L)

print(list(reversed_L))
Output:
['f', 'e', 'd', 'c', 'b', 'a'][Finished in 0.010044827125966549s]
L = ['Ruby', 'Java', 'Python', "C++", "PHP"]

reversed_L = reversed(L)

print(list(reversed_L))
Output:
['PHP', 'C++', 'Python', 'Java', 'Ruby'][Finished in 0.009998386958613992s]

Reverse tuple items

ExampleEdit & Run

Reverse items in a tuple

T = ('Python', 'Java', 'Ruby')

reversed_T = reversed(T)

print(tuple(reversed_T))
Output:
('Ruby', 'Java', 'Python')[Finished in 0.009419958107173443s]

Reverse a string

ExampleEdit & Run

Reversing a string

S = "Hello, World!"

reversed_S = reversed(S)

print("".join(reversed_S))
Output:
!dlroW ,olleH[Finished in 0.010259609902277589s]

In the above example we used the join() method to join the reversed iterator back to a string.

Reverse a range

ExampleEdit & Run

Reverse range items

R = range(10)

reversed_R = reversed(R)

for i in reversed_R:
    print(i)
Output:
9876543210[Finished in 0.010680400067940354s]