As we know that in Python, tuples are immutable, thus it cannot be changed or altered. This provides us with limited ways of reversing a tuple, unlike a list. We will go through few techniques on how a tuple in python can be reversed.
Input : tuples = ('z','a','d','f','g','e','e','k') Output : ('k', 'e', 'e', 'g', 'f', 'd', 'a', 'z') Input : tuples = (10, 11, 12, 13, 14, 15) Output : (15, 14, 13, 12, 11, 10)
Method 1: Using the slicing technique.
In this technique, a copy of the tuple is made and the tuple is not sorted in-place. Since tuples are immutable, there is no way to reverse a tuple in-place. Creating a copy requires more space to hold all of the existing elements. Therefore, this exhausts memory.
('k', 'e', 'e', 'g', 'f', 'd', 'a', 'z')
Method 2: Using the reversed() built-in function.
In this method, we do not make any copy of the tuple. Instead, we get a reverse iterator which we use to cycle through the tuple, similar to the list.
(15, 14, 13, 12, 11, 10)
- Python | Sort tuple list by Nth element of tuple
- Python | Replace tuple according to Nth tuple element
- Python | Reversing a List
- Python | Mean of tuple list
- Python | tuple() Function
- Unpacking a Tuple in Python
- Python | Find whether all tuple have same length
- Python | Convert a list into a tuple
- Python | Difference Between List and Tuple
- Python | Sort lists in tuple
- Python | Unpacking tuple of lists
- Python | Split tuple into groups of n
- Python | Removing strings from tuple
- Python | Get all tuple keys from dictionary
- Python | Remove Consecutive tuple according to key
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.