In this tutorial, we will look at how to swap two elements in a tuple in Python with the help of some examples.
Can you swap tuple elements?
No. Tuples are an immutable data structure in Python and thus cannot be modified after they are created. You can, however, create a new tuple with the required elements swapped.
If you prefer a video tutorial over text, check out the following video detailing the steps in this tutorial –
How to create a new tuple with elements swapped?
If you want to swap elements in a tuple, use the following steps –
Highlighted programs for you
Flatiron School
Flatiron School
University of Maryland Global Campus
University of Maryland Global Campus
Creighton University
Creighton University
- Create a list from the tuple elements.
- Swap the relevant elements in the list using their index.
- Create a new tuple from the list elements.
This will result in a new tuple with the required elements swapped from the original tuple.
Let’s now look at some examples of using this method.
Examples
Let’s create a tuple with three elements – 1, 2, and 3 and then use the above method to swap elements 2 and 3 and get a new tuple.
# create a tuple t = (1, 2, 3) # convert the tuple to list ls = list(t) # swap the elements in the list using their index ls[1], ls[2] = ls[2], ls[1] # create a new tuple from the list elements new_t = tuple(ls) # print the new tuple print(new_t)
Output:
(1, 3, 2)
You can see that the required elements are swapped in the resulting tuple.
Let’s look at another example. This time we will swap the first two elements of a tuple with string values.
# create a tuple t = ('Jim', 'Ben', 'Tom', 'Zack') # convert the tuple to list ls = list(t) # swap the elements in the list using their index ls[0], ls[1] = ls[1], ls[0] # create a new tuple from the list elements new_t = tuple(ls) # print the new tuple print(new_t)
Output:
('Ben', 'Jim', 'Tom', 'Zack')
The resulting tuple has the first two elements swapped from the original tuple.
FAQs
No. Tuples are immutable and thus cannot be modified after creation. You can create a new tuple with the elements swapped.
Create a list from the original tuple values, swap the relevant elements in the list using their index, and create a tuple from the list elements using the tuple()
function.
You might also be interested in –
- Swap Elements in a Python List with these Methods
- Swap Characters in a Python String with this Method
- Easily Swap Keys and Values in a Python Dictionary with this method
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.