How to Reverse a Tuple in Python?

Estimated read time 1 min read

Tuples are immutable in Python, which means their elements cannot be modified once created. However, you can reverse a tuple by creating a new tuple with the reversed order of elements. Here’s an example:

my_tuple = (1, 2, 3, 4, 5)
reversed_tuple = tuple(reversed(my_tuple))
print(reversed_tuple)  # Output: (5, 4, 3, 2, 1)

In this example, we have a tuple my_tuple containing the elements (1, 2, 3, 4, 5). To reverse the tuple, we use the reversed() function, which returns an iterator with the elements in reverse order. We pass this iterator to the tuple() function to convert it back into a tuple, creating the reversed tuple reversed_tuple. Finally, we print the reversed tuple using the print() function, resulting in the output (5, 4, 3, 2, 1).

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply