In this article we are going to discuss the differences between mutable and immutable data types and find a way to change values inside tuples.
In Python we have 4 built-in data types for storing multiple values in one variable. These are lists, dictionaries, sets and tuples. These data structures can be divided into two categories. They can either be mutable or inmutable.
Mutable vs Immutable data types
The main difference is when you use mutable data types like lists or dictionaries you can change the value inside them after assignment.
For example:
list_a = ["first", "second", "third"] # this is a list
print(list_a) # output: ["first", "second", "third"]
list_a[0] = "zero"
print(list_a) # output: ["zero", "second", "third"]
However, in case of a tuple you are not able to do that, because tuples are immutable, meaning the elements inside are unchangable. If we try to change a value in our tuple like this:
tuple_a = ("element1", "element2", "element3")
print(tuple_a) # output: ('element1', 'element2', 'element3')
tuple_a[0] = "element0"
But sometimes we need to change a tuple's value...
So what can we do to make this change?
The easiest solution is to use built-in conversion methods.
Okay, we have 3 remaining data types. Which one should we use?
Well the _dictionaries _ require key, value pairs so in this case using a dictionary wouldn't be a good idea.
We have sets as well. Even though sets are mutable, meaning the values can be changed after assigment, they are not allowing duplicates. So converting a tuple that contains duplicate values (for example two identical string) into a set will result in data loss which we would like to avoid.
So our last candidate is the list. It is mutable, allows duplicates. Seems like a perfect solution!
How can we change the data?
First we need to convert our tuple into a list using the built-in method.
tuple_a = ("element1", "element2", "element3")
tuple_a = list(tuple_a)
print(tuple_a) # output: ["element1", "element2", "element3"]
print(type(tuple_a)) # output: <class 'list'>
After the conversion we get a list. Now we need to change the value to something else.
tuple_a = ("element1", "element2", "element3")
tuple_a = list(tuple_a)
print(tuple_a) # output: ["element1", "element2", "element3"]
print(type(tuple_a)) # output: <class 'list'>
tuple_a[0] = "element0"
print(tuple_a) # output: ["element0", "element2", "element3"]
Finally, we have to convert our list back into a tuple.
tuple_a = ("element1", "element2", "element3")
tuple_a = list(tuple_a)
print(tuple_a) # output: ["element1", "element2", "element3"]
print(type(tuple_a)) # output: <class 'list'>
tuple_a[0] = "element0"
print(tuple_a) # output: ["element0", "element2", "element3"]
tuple_a = tuple(tuple_a)
print(tuple_a) # output: ("element0", "element2", "element3")
print(type(tuple_a)) # output: <class 'tuple'>
And that's it! We have successfully changed the value inside our tuple! 🥳
Top comments (0)