Python | Reverse tuple

Python Methods and Functions

Since we know that in Python, tuples are immutable, so they cannot be changed or changed. This provides us with limited ways to access a tuple as opposed to a list. We will cover several techniques on how you can modify a tuple in python.
Examples:

` 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 slicing technique.
This method creates a copy of the tuple, and the tuple is not sorted in place. Since tuples are immutable, there is no way to reverse a tuple in-place. Making a copy requires more storage space for all existing items. So this is running out of memory.

 ` # Inverting a tuple using the slicing technique ` ` # New tuple created ` ` def ` ` Reverse (tuples): ` ` new_tup ` ` = ` ` tuples [:: ` ` - ` ` 1 ` `] ` ` return ` ` new_tup ` ` `  ` Driver code ` ` tuples ` ` = ` ` (` ` 'z' ` `, ` ` 'a' , 'd' , 'f' , ' g' , 'e' , ' e' , 'k' ) `` print (Reverse (tuples)) `

Output:

` ('k',' e', 'e',' g', 'f',' d', 'a',' z') `

Method 2. Using the built-in reversed () function.
In this method, we do not make a single copy of the tuple. Instead, we get a reverse iterator, which we use to loop through the tuple, similar to a list.

 ` # Flip the list with reversed () ` ` def ` ` Reverse (tuples): ` ` new_tup ` ` = ` ` () ` ` for ` ` k ` ` in ` ` reversed ` ` (tuples): ` ` new_tup ` ` = ` ` new_tup ` ` + ` ` (k,) ` `  print new_tup ``   Driver code tuples = ( 10 , 11 , 12 , 13 , 14 , 15 ) Reverse (tuples) `

Output:

` (15, 14, 13, 12, 11, 10) `