Cyber Monday Sale: save up to $108/year Cyber Monday Sale: subscribe by Nov 28 to save up to $108/year Learn more

Variables are pointers

Trey Hunner smiling in a t-shirt against a yellow wall
Trey Hunner
1 min. read 2 min. video Python 3.7—3.11
Share
Copied to clipboard.

Variables in Python are not buckets that contain things, but pointers: variables point to objects.

Assignments point a variable to an object

Let's say we have a variable x which points to a list of 3 numbers:

>>> x = [1, 2, 3]

If we assign y to x, this does something kind of interesting:

>>> y = x
>>> x == y
True

The variable x is equal to the variable y at this point, x and y also have the same id, meaning they both point to the same memory location.

>>> id(x)
140043174674888
>>> id(y)
140043174674888

Mutating an object that 2 variables point to

When two variables have the same id, those two variables both point to the same object. So if we mutate the object x points to (by appending to that list) x will now have 4 in it but so will y!

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

The reason this happens is all about the line that we wrote above:

>>> y = x

Assignments don't copy anything

Assignment statements never copy anything in Python. Assignments take a variable name and point them to an object.

Variables are not buckets; they're pointers

When I say variables are pointers, I mean they're not buckets that contain things.

When you do an assignment, you're pointing the variable name on the left-hand side of the equals sign (y in this case) to whatever object is referenced on the right-hand side of the equals sign (the list that x already happens to point to in this case).

So variables in Python are pointers, not buckets that contain things.

Sale Through November 28 💸

Subscribers get customized weekly recommendations for exercises and screencasts and access over 300 screencasts, exercises, and articles.

Save up to $108 per year if you subscribe by November 28.

Save on Python screencasts and exercises

Series: Assignment and Mutation

Python's variables aren't buckets that contain things; they're pointers that reference objects.

The way Python's variables work can often confuse folks new to Python, both new programmers and folks moving from other languages like C++ or Java.

To track your progress on this Python Morsels topic trail, sign in or sign up.

0%
Concepts Beyond Intro to Python

Intro to Python courses often skip over some fundamental Python concepts.

Sign up below and I'll share ideas new Pythonistas often overlook.