Tuples in Python are sequence of elements, but these are immutable meaning once created tuple remains unique throughout program and it’s elements cannot be updated. But what if you need to swap some elements in a Tuple, for example – If you need to change tuple (1, 3, 5) to (1, 5,3) swapping elements at index 1 with that at index 2 in Tuple.
Let’s see How swapping of elements in a Tuple can be done?
For swapping elements in a tuple, first convert tuple to list then do swapping of elements and convert list back to tuple. That’s it elements in tuple have been swapped.
Python Code for Swapping Elements in a Tuple
# Python Code for Swapping Elements in a Tuple x = (27, 38, 28, 16, 26, 7) # Conver tuple x to list list_x = list(x) # Swapping element at index 1(38) with element at index 3(16) in list_x list_x, list_x = list_x, list_x # Converting list back to tuple final_tuple = tuple(list_x) # Final List after swapping elements print("Tuple after doing swapping of elements is =>", final_tuple)
Output of Above Code
Tuple after doing swapping of elements is => (27, 16, 28, 38, 26, 7)