Mutable and Immutable Objects

Unlike strings, bracket notation can also be used to change individual items of a list.


>>> names[3] = "Ringo"
                        

>>> names
["John", "Paul", "George", "Ringo"]
                    

Changing lists needs to be done with care. In Python, when we use the = operator to "copy" a list to another variable, the list is not actually replicated. Instead, both variables now simply point to the same list. Note: This is the same behavior that happens in Snap!, which you may remember from the lists lab.


>>> beatles = names
                    

>>> beatles
["John", "Paul", "George", "Ringo"]
                    

When an item (a.k.a element) of beatles is changed, the associated names list is also changed.


>>> beatles[2] = "Alonzo"
                    

>>> beatles
["John", "Paul", "Alonzo", "Ringo"]
>>> names
["John", "Paul", "Alonzo", "Ringo"]

                    

This is an important property of Python. Mutability is the ability for certain types of data to be changed without entirely recreating it. Using mutable data types can allow programs to operate quickly and efficiently.


Mutability varies between different data types in Python. A list is mutable, as demonstrated above. Conversely, a string is not mutable, or immutable. Modifying a string creates a new one as demonstrated here:


>>> a = "potato"
>>> b = a
>>> a += a
>>> a
"potatopotato"
>>> b
"potato"
        

You may have noticed that this behavior is exactly the same as what happens in Snap!. In Snap! lists are mutable and strings are immutable.

To make a completely separate copy of a list, use the [:] operator. This operator iterates through every item of the list and copies each item into a new list.


>>> your_music = ["Billy Jean", "Day Tripper", "Bohemian Rhapsody"]
>>> my_music = your_music[:]
>>> my_music
["Billy Jean", "Day Tripper", "Bohemian Rhapsody"]
        

If an item of the original list is modified, the copy remains unchanged.


>>> your_music[1] = "Time"
>>> your_music
["Billy Jean", "Time", "Bohemian Rhapsody"]
>>> my_music
["Billy Jean", "Day Tripper", "Bohemian Rhapsody"]
        

Even though an entry of your_music is modified, my_music remains as it was originally copied.