Notes Tutorials

Memory: values and references

Why changing one variable sometimes changes another. Values vs references, shallow vs deep copies, garbage collection, and the Python default-argument trap, with real output.

6 min readAlso available in Bahasa Indonesia →

Sooner or later every programmer writes something like this and gets surprised:

x = [1, 2, 3]
y = x
y.append(4)
print(x)   # [1, 2, 3, 4]

We only changed y. Why did x change too? The answer is one of the most useful things to understand early: the difference between a value and a reference. The previous part looked at what bits in memory mean. This part looks at how variables point to them.

Variables are names, not boxes

A common way to explain variables is “a box that holds a value”. That picture works for small things like numbers, but it breaks down for lists, objects, and anything larger. A more accurate picture: a variable is a name that points to something in memory.

The Python FAQ says it directly: “Variables are simply names that refer to objects.” And about the example above: “Doing y = x doesn’t create a copy of the list – it creates a new variable y that refers to the same object x refers to.” There is only one list in memory. Two names point at it.

>>> x = [1, 2, 3]
>>> y = x
>>> y.append(4)
>>> x
[1, 2, 3, 4]
>>> x is y
True

is checks whether two names point to the same object. Here they do.

Then why do numbers seem to behave differently?

>>> n = 10
>>> m = n
>>> m = m + 1
>>> n, m
(10, 11)

Nothing surprising here, and the reason is not that numbers are “copied”. m = m + 1 creates a new number object (11) and points m at it. n still points at 10. The difference is between changing an object (append modifies the list in place) and pointing a name at a different object (= with a new value).

Numbers and strings in Python can’t be changed in place (they are immutable), so you only ever get the second kind. Lists, dictionaries, and most objects can be changed in place (they are mutable), so sharing them means sharing their changes.

JavaScript works the same way for objects

const user = { name: "Rama" };
const other = user;
other.name = "Budi";
console.log(user.name);           // Budi

const copy = { ...user };
copy.name = "Sari";
console.log(user.name, copy.name); // Budi Sari

other = user shares the object. { ...user } creates a new object with the same properties, so changing copy leaves user alone.

PHP: arrays are copied, objects are shared

PHP is the odd one out, and if you come from PHP this is worth knowing before switching languages. The manual says: “Array assignment always involves value copying. Use the reference operator to copy an array by reference.”

$a = [1, 2, 3];
$b = $a;
$b[] = 4;
echo json_encode($a), " ", json_encode($b);   // [1,2,3] [1,2,3,4]

$c = &$a;      // explicit reference
$c[] = 99;
echo json_encode($a);                          // [1,2,3,99]

So code that is perfectly safe in PHP ($b = $a; $b[] = 4;) changes the original when you write the same thing in Python or JavaScript.

Objects behave like the other languages, with a footnote. The manual warns that “objects are passed by reference by default” is “not completely true”: a variable holding an object “only contains an object identifier which allows object accessors to find the actual object.” In practice, two variables share the same object, and clone makes a separate one:

$user = new stdClass();
$user->name = "Rama";
$other = $user;
$other->name = "Budi";
echo $user->name;                  // Budi

$copy = clone $user;
$copy->name = "Sari";
echo $user->name, " ", $copy->name; // Budi Sari

Go makes the difference visible

Go is useful here because it has both behaviors side by side. The Go blog’s article on slices says: “Go’s arrays are values. This means that when you assign or pass around an array value you will make a copy of its contents.” Slices are different: “A slice is a descriptor of an array segment”, and “Slicing does not copy the slice’s data.”

arr := [3]int{1, 2, 3}
arrCopy := arr
arrCopy[0] = 99
fmt.Println(arr, arrCopy) // [1 2 3] [99 2 3]

s := []int{1, 2, 3}
t := s
t[0] = 99
fmt.Println(s, t)         // [99 2 3] [99 2 3]

u := make([]int, len(s))
copy(u, s)
u[1] = 42
fmt.Println(s, u)         // [99 2 3] [99 42 3]

The array was copied, so changing arrCopy left arr untouched. The slice was shared, so changing t changed s. To get an independent slice, you copy it explicitly.

Shallow and deep copies

Copying has its own trap. The Python copy module documentation starts with: “Assignment statements in Python do not copy objects, they create bindings between a target and an object.” When you do want a copy, there are two kinds:

  • A shallow copy “constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.”
  • A deep copy “constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.”

The difference only shows up with nested data:

>>> import copy
>>> a = [[1, 2], [3, 4]]
>>> s = copy.copy(a)       # shallow
>>> d = copy.deepcopy(a)   # deep
>>> a[0].append(99)
>>> s
[[1, 2, 99], [3, 4]]
>>> d
[[1, 2], [3, 4]]

The shallow copy is a new outer list, but its inner lists are the same ones as in a. The deep copy copied everything.

A classic trap: mutable default arguments

The Python tutorial has an “Important warning” for exactly this: “The default value is evaluated only once.” That matters when the default is “a mutable object such as a list, dictionary, or instances of most classes”:

def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item("a"))  # ['a']
print(add_item("b"))  # ['a', 'b']   ← not ['b']

The empty list is created once, when the function is defined, and every call that uses the default shares it. The usual fix:

def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

print(add_item("a"))  # ['a']
print(add_item("b"))  # ['b']

Stack, heap, and who cleans up

You’ll often hear two words for where data lives:

  • The stack holds short-lived data for the function that is currently running: its local variables and where to return to. It is cleaned up automatically when the function returns.
  • The heap holds data that needs to outlive a single function call, like objects and lists that get passed around.

The exact rules differ by language and compiler, and in Python, JavaScript, and Go you rarely decide this yourself. What you do need to know is that heap memory has to be freed at some point. In languages like C, the programmer frees it manually. In Python, JavaScript, and Go, a garbage collector does it. MDN describes it for JavaScript: it “automatically allocates memory when objects are created and frees it when they are not used anymore.”

“Not used anymore” means nothing points to it. That is also how memory leaks happen in garbage-collected languages: something you forgot about, like a cache, a global list, or an event listener, is still holding a reference, so the memory can never be freed.

Why this matters day to day

  • Unexpected changes. A function that modifies a list or object it received changes it for the caller too. If that isn’t the intent, copy first or return a new value.
  • State in front-end apps. Frameworks that detect changes by comparing references (like React) won’t notice if you modify an object in place. That’s why you often see { ...state, field: value }.
  • Shared defaults and caches. Mutable defaults, module-level lists, and caches are shared by everyone who uses them, sometimes across requests on a server.
  • Memory leaks. In garbage-collected languages, leaks are usually forgotten references, not forgotten free calls.

Try it yourself

  1. Run the x/y list example, then change y = x to y = x.copy() and run it again.
  2. Run the shallow vs deep copy example with a dictionary of lists instead of a list of lists.
  3. In your browser console, create an object, assign it to a second variable, change a property through the second one, and log the first.
  4. If you have Go installed, write a function that takes an array and one that takes a slice, change the first element inside each, and print the original afterwards.

Summary

  • A variable is a name that points to something in memory, not a box that holds it.
  • Assigning a mutable object to another variable shares it; it doesn’t copy it.
  • Changing an object in place is different from pointing a name at a new object.
  • Go arrays and PHP arrays are copied on assignment; Go slices share their underlying array; PHP objects are shared until you clone them.
  • A shallow copy shares nested objects; a deep copy copies everything.
  • Python evaluates default argument values once, so never use a mutable default.
  • Garbage collectors free memory that nothing points to; leaks come from references you forgot.

References