Immutable vs Mutable Objects (Python)
In the Python programming language, everything is an object. Not all objects in Python handle change the same way. Before going on further to explain, I’ll need to define some important terms. First, a class in Python is essentially a blueprint created by a programmer for an object. It defines a set of attributes that will characterize any object that is instantiated from that specific class. An object on the other hand, is an instance of a class. This is the realized version of the class, where the class is manifested in the program. Specifically, the different types of objects I’ll be discussing include mutable and immutable objects.
id() and type()
In order to better understand mutability, it would be beneficial to talk about Python’s built-in id and type functions. The id function returns the identity of an object. This is guaranteed to be unique among simultaneously existing objects. It basically returns the object’s memory address. For instance:
>>> a = 7
>>> id(a)
35143880 In this snippet of code, we assigned the variable a to the integer 7. Calling the id function with a as a parameter then returns the integer’s memory address on the next line. The type function on the other hand returns an objects type. For example:
>>> a = 7
>>> type(a)
<type 'int'>In this snippet of code, we simply call the type function with a as an argument. The objects type is displayed on the next line. Now that we have these two tools at our disposal, we can now start discussing mutable an immutable types.
Mutable Objects
In Python, some common mutable objects include lists, dicts, and sets. In simple terms, when an object is referred to as being mutable, it means that the object, or the contents of that object can be altered. A good way to think about which types are mutable and which are not is that containers and user-defined types are usually mutable while scalar types are almost always immutable. Notable exceptions for this logic includes a tuple, which is a container but is immutable, and a frozenset. A frozenset is an immutable version of a set. say for example that you had a list of things to do as follows:
>>> to_do = ['laundry', 'read', 'taxes']After getting back from a long day of work, the last thing you want to do is your taxes, so you decide to take that off your list like so:
>>> to_do.pop(2)
'taxes'
>>> print(to_do)
['laundry', 'read']Instead of doing your taxes, you’d rather relax with a cold beverage in hand, so lets make that happen.
>>> to_do.append('cold_one')
>>> print(to_do)
['laundry', 'read', 'cold_one']We were able to easily manipulate our list because its mutable. If we had a list for two different days like so:
>>> to_do1 = ['groceries', 'gym', 'cook']
>>> to_do2 = ['groceries', 'gym', 'cook']
>>> id(to_do1), id(to_do2)
(140395611717000, 140395611716928)We could use the id function to check the memory address of each list. As we can see, the memory addresses are different, so although, the lists have the same value, they point to different places in memory. This is important to note because more likely than not, if the memory address is different while the value is the same, then the object is mutable.
Immutable Objects
Common immutable objects in Python include ints, floats, tuples, and strings. Unlike mutable objects, the immutable objects can’t be changed. Instead, they return a new object entirely if they are updated. We’ll use our tax example again, but this time they’ll be in a tuple and not a list.
>>> to_do = ('laundry', 'read', 'taxes')Now that we have our tuple, we’ll try to use the pop attribute that we used before to remove taxes from the tuple.
>>> to_do.pop(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'pop'Since a tuple is not a list, we got an error because the pop method is not available to tuples. Instead, lets try to assign an empty string to the index where taxes is:
>>> to_do[2] = ""
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignmentAgain, we are met with an error. This error tells us that tuples don’t support item assignment. That’s Python’s way of politely saying, you can’t change this object. Seems like there’ll be no cold ones for us this time. Another example of an object we won’t be able to change is a string.
my_string = "Avadakedavra"For our string, we are using a well know magic spell. Let us attempt to change the letter k to q.
>>> my_string[5] = 'q'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignmentOnce again, we get the error informing us that we can’t change the object. If we were to create another variable for the string, we would be able to us the id function to check both memory addresses like so:
>>> my_string = "Avadakedavra"
>>> my_spell = "Avadakedavra"
>>> id(my_string), id(my_spell)
(140395550790560, 140395550790560)As we can see, although two different variable names have been assigned to the string, the id function still shows that they point to the same memory address. Unlike mutable objects, when the memory addresses are the same despite having different variable names, the object is immutable.
So what?
Although mutability might not seem like an important concept, it becomes crucial when trying to write efficient programs. For instance, to concatenate a string, one could do the following:
my_string = ""
for word in words:
my-string += str(data)Although this program would work, it is extremely inefficient. Since strings are immutable, concatenating two strings actually creates a third string which is a combination of the previous two. If you are iterating over a lot of text to build a large string, a lot of memory will be used to create and discard the objects as the program is running. A more efficient way to do the same thing would be as follows:
"".join(str(word) for word in words)This code takes advantage of the mutability of a list object to gather the words together and then allocates a single result string to put the combination of all the words in. This reduces the amount of memory used by the program.
Passing Immutable and Mutable Arguments to Functions
Although we now understand what exactly mutable and immutable objects are, we still need to examine how these objects behave when they are passed to functions. There are mainly two ways that objects get passed to functions. Passing by reference means that the called functions parameter will be the same as the caller’s passed argument. On the other hand, pass by value means the called function’s parameter will be a copy of the caller’s passed argument. First we’ll pass an immutable object to a function:
>>> def increment(n):
... n += 1>>> a = 3
>>> increment(a)
>>> print(a)
3 # a is still referring to the same object
In this example, we get the result 3 because we are unable to modify the value that a is assigned to since its an integer, which is immutable. After a gets passed to the increment function, we create a new variable n within the function to hold the value after adding one to the previous value of a so that now, n = 4. When we call the print statement at the end, a is still referencing the value 3.
Get Afa Madza’s stories in your inbox
Join Medium for free to get updates from this writer.
Now, we’ll pass a mutable object to a function and see how it behaves.
>>> def increment(n):
... n.append([4])>>> l = [1, 2, 3]
>>> increment(l)
>>> print(l)
l = [1, 2, 3, 4] # l changed
In the above snippet of code, we assign the variable l to a list containing the integers 1,2 & 3. We then pass l to the increment function as a parameter. The .append method simply adds the integer 4 to the end of the list. From previous examples, we’ve demonstrated that lists are mutable, so we are able to change their values in place. Although we have not created a new object, when we print l the list is updated because it is mutable.
The concept of mutability is one that has plagued many a fledgling programmer, so I hope I’ve been able to help a bit. happy coding my friends!










