Memory Model

It can be confusing to predict what Python (or any computer programming language) will do when you are copying values from one location to another if you don't have a good mental model of what actually happens when you do a copy. Consider this code:

In [ ]:
x = 5
y = x
x = x + 1

What will the value of y be after this is run? Type it in and try it.

In [ ]:
print(y)

By now you should understand that at the time that y was assigned the value of x, x had the value 5. Then x's value changed after that assignment. That doesn't affect the value of y. But what about this?

In [ ]:
L1 = [1, 2, "hello"]
L2 = L1
print("L2 is", L2)
L1[1] = 'surprise'

How what is the value of L2?

In [ ]:
print("L2 is", L2)

But notice that L2 was assigned its value at the point when L1 has [1, 2, 'hello']. In fact, we printed that out. L2 really did have 2 as its second element. So why did it change when L1 was changed? In order to see this look at this same code in the Python visualizer

Notice that there is only one list. When we assign L2 to L1, we don't make a copy of L1. We assign L2 to reference the same List as L1. Now consider this code.

In [ ]:
L3 = ['green', 'eggs', 'and', 'ham']
L4 = L3[1:]
print('L3 is', L3)
print('L4 is', L4)

L4[0] = 'cheese'

What is your prediction of the values of L3 and L4? Use the visualizer to check if you were correct.

Practice Exercises

Predict the output of each of the code fragments below and then run the code, either in the Python visualizer or in Wing to make sure your model is correct.

In [ ]:
L = ['a', 'b', 'c']
result = L[2]
L[2] = 5
print('L is', L)
print('result is', result)
In [ ]:
inner = ['A','B','C','D']
outer = [inner, 'gap', inner[:]]
inner.append('E')
print(outer)
In [ ]:
vowels = ['a','e','i','o','u']
others = ['C','M']
letters = [vowels, others]
copy = letters[:]
# add y to the vowels
vowels.append('y')

print('letters is', letters)
print('copy is', copy)
In [ ]:
# now add another set to letters
letters.append(['Q','R','S'])
print('letters is', letters)
print('copy is', copy)

Carefully look at the last two examples: In the first, both copies changed to add 'y', but in the second example only letters gained Q,R & S. If you didn't predict this and can't explain why it happens, use the visualizer one more time.