Are Tuples Mutable in Python
As of now, we are familiar with some things in relation to the tuple, like how we can create tuples, and how we can access the individual tuple elements as well. Now, we need to have a look at whether or not are tuples mutable. Basically, we need to check if we can access the tuple elements and if can even we change them. Let’s have a look at the below program, which tries to demonstrate the same thing.
Are Tuples Mutable in Python
As you can see, in the above program, we are having a tuple, and then in the next line, we are trying to access the individual tuple element, and perform some assignment. Well, we go into errors if we do so. The thing is that the tuples are immutable, which means that we cannot alter, add, or remove the elements in the tuple. If we try to do so directly on a tuple element, we get into an error. The error simply says that – TypeError: ‘tuple’ object does not support item assignment. So, we cannot simply directly make changes here.
But now, if we are required to make changes to the tuple, we just saw that we are not able to do so. But there is something else that we can do. In order to make some changes to the tuple, we can first convert that tuple to a list, and then make those changes on the list, and then change it back to a tuple.
Let’s have a look at the below program, which tries to demonstrate the same thing.
As you can see, in the above program, we have a tuple, and we know that we cannot make changes in the tuple now, so we first convert the tuple to a list, and then try to make the changes, and then convert it back to a tuple. When we print the tuple, we can simply see that we have the tuple with the respective changes.
So, if you want to make some changes to the tuple, we cannot directly do so, but we can convert it into a list, and then make the changes and convert it back to a tuple.
The thing is that we can even complicate things, by having a tuple inside a tuple, or some other sequence like list, or string in the tuple. This can be according to the requirement. We can have multiple data of different datatype, and also, we can have duplicate values. So, we can make use of the tuples in our programs as and when required.