Python Immutable – Can not edit

In Python, immutable means you are not able to edit something. Mutable means you are. This is due to the way the data types are created in Python. Don’t fear, this isn’t a blocker, there is always a solution if you run into a problem.

The common types of immutable data are int, float, bool, str, tuple.

my_string = "Data"
my_string[2] = "T

>>> TypeError: 'str' object does not support item assignment

Python Immutable

If you run into an immutable object, and you need to edit it, then you’ll need to change the data type. For example: change your tuple to a list, or dict.

Let’s look at a quick code sample


Python Immutable

In python, immutable means you can't edit or change something. Mutable means you can. For example, you can't assign values in a tuple, but you can in a list. Let's take a look

Mutable Objects

In [3]:
my_list = [1,2,3,4,"Bob"]
my_list
Out[3]:
[1, 2, 3, 4, 'Bob']
In [5]:
my_list[0] = "New first position"
my_list
Out[5]:
['New first position', 2, 3, 4, 'Bob']
In [9]:
my_dictionary = {"City1" : "San Francisco", "City2" : "Los Angeles"}
my_dictionary
Out[9]:
{'City1': 'San Francisco', 'City2': 'Los Angeles'}
In [11]:
my_dictionary["City1"] = "Austin"
my_dictionary
Out[11]:
{'City1': 'Austin', 'City2': 'Los Angeles'}

Immutable Objects

In [12]:
my_tuple = (1,2,3)
my_tuple
Out[12]:
(1, 2, 3)
In [13]:
my_tuple[1] = 100
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-436381ca19c9> in <module>
----> 1 my_tuple[1] = 100

TypeError: 'tuple' object does not support item assignment
In [14]:
my_string = "My String"
my_string[2] = "T"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-c26aafa90582> in <module>
      1 my_string = "My String"
----> 2 my_string[2] = "T"

TypeError: 'str' object does not support item assignment
In [24]:
my_set = set([1,2,3,4])
my_set.add(5)
my_set
Out[24]:
{1, 2, 3, 4, 5}
In [25]:
my_set[2] = "Ted"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-7357ae5e7be5> in <module>
----> 1 my_set[2] = "Ted"

TypeError: 'set' object does not support item assignment
In [26]:
my_frozenset = frozenset([1,2,3,4])
my_frozenset.add(10)
my_frozenset
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-26-76aa41094cfb> in <module>
      1 my_frozenset = frozenset([1,2,3,4])
----> 2 my_frozenset.add(10)
      3 my_frozenset

AttributeError: 'frozenset' object has no attribute 'add'

Link to code above

Check out more Python Vocabulary on our Glossary Page