Assignment for Mutable Data Types#

Will Trimble

Python’s equals sign has different behavior for different data types.

Immutable data types include strings, numbers, and tuples. Immutable data types and expressions copy by value.

Mutable data types include lists, dictionaries, sets, and more complicated data types. These require explicit copying.

Mutable data types include lists, dictionaries, sets, and most more complicated data types. These require explicit copying.

For immutable data types, the = is the assignment operator: the right hand side of the expression is evaluated and the value is copied into the name on the left hand side of the = sign.

For mutable data types, = gives a new name to the same object. The data is not copied, and exists in only one place in the computer’s memory. The same data now has two names, both of which can be used to change it. This may have unintended effects:

list1 = [1,2,3]
list2 = list1  # this does not create a new list
list1[2] = 6   # since there is only one list, changing list1
print(list1)
print(list2)   # changes list2.
[1, 2, 6]
[1, 2, 6]

If you need a second copy of a mutable object, you must copy it explicitly. Mutable data types have a .copy() method that will create a new copy that can be altered separately from the original:

list3 = [1,2,3]
list4 = list3.copy()
list3[2] = 8
print(list3)
print(list4)  
# Success!  list3 can finally have different values from list4
[1, 2, 8]
[1, 2, 3]

Can you follow what is happening to the strings here? Can you predict which animal is assigned to different variables?

animal1 = "dog"
animal2 = "cat"
animal3 = "procupine"
animal4 = animal3
animal3 = animal2
animal2 = animal1
animal1 = animal3 
# This line will display the contents of these four strings
animal1, animal2, animal3, animal4
('cat', 'dog', 'cat', 'procupine')