Python's Memory Model Is Not What You Think It Is
Python's Memory Model Is Not What You Think It Is Ask most Python developers how Python stores a variable and they will say "it stores the value." This is imprecise in a way that causes real bugs and real confusion in interviews. A precise mental model of how Python stores and retrieves data changes how you read and write code. Python does not store values in variables. Python binds names to objects. The distinction sounds philosophical until you trace code that involves mutation, function arguments, or aliasing. Then it becomes the most practically useful concept in the language. Names Are Not Boxes The box metaphor, which says a variable is a box that holds a value, is how most introductory programming courses explain variables. In many languages this metaphor is close enough to accurate that it does not cause problems. In Python it is wrong in ways that matter. A more accurate metaphor: a Python name is a label attached to an object. The object exists independently in memory. Multiple labels can be attached to the same object. Attaching a new label does not move or copy the object. x = [ 1 , 2 , 3 ] y = x print ( id ( x ) == id ( y )) # True (same object, two labels) When you write y = x , you are not copying the list. You are creating a second label that points to the exact same list object. The Four Operations You Must Distinguish 1. Assignment creates a new binding x = [ 1 , 2 , 3 ] x = [ 4 , 5 , 6 ] # x now labels a completely different object The first list still exists in memory until garbage collected. The name x simply stops pointing to it and now points to the second list. 2. Mutation modifies an existing object x = [ 1 , 2 , 3 ] x . append ( 4 ) # the object x labels is modified in place Any other name pointing to the same object will instantly reflect this change because they look at the same memory location. 3. Augmented assignment on mutable types mutates x = [ 1 , 2 , 3 ] y = x x += [ 4 , 5 ] print ( y ) # [1, 2, 3, 4, 5] (same object, mutated) The