1.8. Memory management in Python#
The memory model for comprehending how variables are stored in Python differs from that of other programming languages. In many programming languages, variables can be likened to named storage locations in computer memory—essentially boxes where we can place values. When a variable changes, the previous value is overwritten by a new one.
In Python, values can be stored anywhere in memory, and variables are employed to reference them. Assigning a variable is analogous to placing a small yellow sticky note on the value and declaring, ‘this is x.’ This memory model is commonly referred to as the sticky-note model. Put another way, a Python variable is a symbolic name that is a reference or pointer to the value, which is technically an object.
What happens when we execute the following statement?
<<variable>> = <<expression>>
This is executed as follows:
Evaluate the expression on the right of the
=
sign to produce a value. This value has a memory address. We can call this an object: a value at a memory address with a type.Store the memory address of the value in the variable on the left of the
=
. Create a new variable if that name does not already exist; otherwise, just reuse the existing variable, replacing the memory address that it contains.
difference = 20
double = 2 * difference
print(double)
difference = 5
print(double)
40
40
number = 3
print(number)
number = 2 * number
print(number)
number = number * number
3
6
You can use Python Tutor to view how the sticky-notes change.