Are Lists Mutable in Python? (Examples)
On this page, we’ll discover if lists are mutable in Python programming. The article will consist of an introduction to mutability, examples of how mutable and immutable objects work differently, and some final notes. More precisely, the content of the post looks as follows:
Let’s do this!
Introduction to Mutability
In Python, an object’s mutability is determined by whether its state or value can be modified after it has been created. There are mutable and immutable objects in Python.
Mutable Objects: These can be altered after creation. Examples include lists, dictionaries, and sets.
Immutable Objects: Their state cannot be modified after creation. Examples include numbers, strings, and tuples.
Let’s discover if Python lists are mutable with examples! First, we need to create a sample list to be used in examples.
Example Data
The following data is used as a basis Python list in this tutorial.
fruits = ["apple", "banana", "cherry"] # create sample list print(fruits) # print fruits list # ['apple', 'banana', 'cherry']
As you can see, our sample list is a list containing three elements. Let’s now check if we can modify this created list. If we can, it will provide evidence that lists are mutable in Python.
Examples: Mutability of Lists
In this example, we will try to modify the fruits
list by replacing the element in a given index. Let’s see if it is possible!
fruits[0] = "grape" # replace elements in fruits print(fruits) # print updated fruits list # ['grape', 'banana', 'cherry']
As observed above, the first element of fruits
returned to "grape"
from "apple"
.
Of course, we can also do other modifications. For example, we can append a new element to the existing list. Let’s show it with another example!
fruits.append("orange") # append new element to fruits print(fruits) # print update fruits list # ['grape', 'banana', 'cherry', 'orange']
We have illustrated the mutable nature of lists already twice. Let’s check out how immutable objects respond when we attempt to modify them in the next examples!
Examples: Immutability
In this section, first, we will try to alter a string object. Follow the script below.
str1 = "Hello" # create sample string str1[0] = "J" # modify string # TypeError: 'str' object does not support item assignment
As seen, we couldn’t change the first letter of the string str1
. An error indicating the inapplicability of item assignment has been returned.
You might be wondering What if we use a valid string operation? To illustrate this, I will use the concatenation operation used to concatenate string objects. We will use the previously created string str1
in our example.
str1 + "oo!" # concatenate "oo!" to string # 'Hellooo!' print(str1) # print string # "Hello"
As you can see, the string "oo!"
was successfully added to the initial string str1
. However, when we print str1
, the initialized value "Hello"
was returned due to its immutable nature.
If you would like to reference str1
to a new value in Python, you have to create a new string like str1 = str1 + "oo!"
. As a result, str1
will point to this new object value rather than the original. If there are no other references to this old string, it will be cleaned up from memory.
Before ending this tutorial, let’s mention some other implications of immutability and mutability.
Notes & Caveats
The fact that we can alter Python lists does not imply that we can alter the immutable objects within lists. Let’s demonstrate it using our sample list fruits
.
fruits[2][0:2] = "b" # modify string in new_list # TypeError: 'str' object does not support item assignment
As you can see, I can not replace the first two letters of "cherry"
with "b"
to create a new string "berry"
even though the list itself is mutable.
Another implication of mutabilty is that when you assign a list to another variable, modifications to one will reflect in the other. So let’s create a new reference to our sample list fruits
and check if the changes in the new reference affects our fruits
list.
new_list = fruits # assign fruits to new_list new_list[0] = 10 # modify new_list print(new_list) # print new_list # [10, 'banana', 'cherry', 'orange'] print(fruits) # print fruits # [10, 'banana', 'cherry', 'orange']
As celarly seen, the modification in new_list
reflects in the fruits
list. If you want to avoid this feature, you have to make a copy of the list.
Video & Further Resources
I have recently published a video on my YouTube channel, which shows the Python syntax of this tutorial. You can find the video below:
The YouTube video will be added soon.
Furthermore, you might read some of the other articles on my homepage. I have published several related articles already:
- How to Use Lists in Python
- Replace Element at Certain Index in List in Python
- Append to Empty List in Python
- Make Copy of List With & Without Reference in Python
- All Python Programming Examples
Summary: This page has explained how to explore if lists are mutable in the Python programming language. If you have further questions and/or comments, let me know in the comments below.
This page was created in collaboration with Cansu Kebabci. Have a look at Cansu’s author page to get more information about her professional background, a list of all his tutorials, as well as an overview on her other tasks on Statistics Globe.