Python | Swapping Two Elements in a Tuple

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[1], list_x[3] = list_x[3], list_x[1]

# 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)

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts