In Python, there are mutable and inmutable data types. Mutable data types can be changed after it has been created. Inmutable data types cannot be changed after they have been created.
Are tuples mutable in Python?
No, tuples are not mutable in Python and are inmutable.
With tuples, we cannot add or remove elements of a tuple, or change the tuple’s items.
For example, let’s say we have the following tuple.
t = (0, 1, 2)
There are no tuple methods which allow us to add or remove elements, such as append() or pop(), like other data types have.
Also, if you try to change an item in a tuple, then you will get the following TypeError.
t = (0, 1, 2)
t[0] = 2
#Output:
TypeError: 'tuple' object does not support item assignment.
Given these properties of tuples, we’ve now know that tuples are not mutable.
Examples of Mutable Data Types in Python
Some data types which are mutable in Python include lists, dictionaries, sets and user-defined classes.
For example, with lists, we can add items to a list, remove items from lists, and easily change the items in a list.
Dictionaries are also mutable because we can add new key/value pairs, remove existing key/value pairs, change the name of the keys and change existing values.
Basically, if an object can be change over time, then it is mutable. If it cannot change, then it is inmutable.
Hopefully this article has been useful for you to learn that tuples are not mutable and about mutable data types in Python.