Write a Python program to reverse a tuple


The program is written in Python and it declares a tuple a with eight integer values. The program then prints the original tuple a using the print function with the message "Before Reverse :". Next, the program provides three methods to reverse the tuple a.

  • The first method uses slicing to reverse the tuple a. The slice a[::-1] starts from the end of the tuple and goes to the beginning, with a step of -1. This results in a new tuple that is the reverse of the original tuple a.
  • The second method converts the tuple a to a list using the list function, reverses the list using the reverse method, and then converts the reversed list back to a tuple using the tuple function.
  • The third method uses the reversed function to reverse the tuple a. The reversed function returns a reverse iterator over the elements of the tuple. The reverse iterator is then converted to a tuple using the tuple function.
  • The reversed tuple is printed on the console for each of the three methods using the print function with the message "After Reverse :".

Source Code

a = (23,45,67,78,89,90,34,56)
print("Before Reverse :",a)
"""
#First Method
print("After Reverse :",a[::-1])
 
#Second Method
b = list(a)
b.reverse()
a = tuple(b)
print("After Reverse :",a)
"""
#Third Method
y = reversed(a)
print("After Reverse :",tuple(y))
 

Output

Before Reverse : (23, 45, 67, 78, 89, 90, 34, 56)
After Reverse : (56, 34, 90, 89, 78, 67, 45, 23)


Example Programs