Andromeda
Note

References (Python)

Definition

Values that represent memory addresses, rather than the data itself. In Python, variables do not “contain” mutable objects like lists; they store references to those objects.

Why It Matters

Misunderstanding references leads to ‘spooky action at a distance’ where changing one variable unexpectedly mutates another. In complex systems, this creates non-deterministic bugs that are nearly impossible to trace without a clear mental model of memory addressing.

Core Concepts

  • The “Name Tag” Model: Instead of a variable being a “Box” that holds data, it is a “Name Tag” attached to an object in memory. Assignment (b = a) just attaches a second name tag to the same object.
  • Side Effects: Because multiple variables can point to the same reference, modifying the object via one variable affects all others (e.g., spam.append() modifies the list that cheese also points to).
  • Function Arguments: When you pass a mutable object (like a list) to a function, you are passing a reference. Any changes the function makes to the list persist after the function returns.
  • Copying:
    • copy.copy(list): Creates a new list with a new reference, but nested objects are still shared (shallow copy).
    • copy.deepcopy(list): Recursively copies all objects, ensuring total independence (deep copy).
# Shared references
spam = [0, 1, 2, 3, 4, 5]
cheese = spam # Both point to the same list
cheese[1] = 'Hello!'

print(spam)   # [0, 'Hello!', 2, 3, 4, 5]
print(cheese) # [0, 'Hello!', 2, 3, 4, 5]

Connected Concepts