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.
Variables in Python are not buckets that contain things, but pointers: variables point to objects.
Let's say we have a variable
x which points to a list of 3 numbers:
>>> x = [1, 2, 3]
If we assign
x, this does something kind of interesting:
>>> y = x >>> x == y True
x is equal to the variable
y at this point,
y also have the same
id, meaning they both point to the same memory location.
>>> id(x) 140043174674888 >>> id(y) 140043174674888
This means they 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
>>> 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
Assignment statements never copy anything in Python. Assignments take a variable name and point them to an object.
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.
Hello friendly web visitor! 👋
This page is part of Python Morsels, an online Python skill-building service.
The best way to learn is by doing. In the case of Python that means writing Python code. If you'd like to improve your Python skills every week, try out Python Morsels by entering your email below to create an account.
Python Morsels topics pages are free and the first month's worth of exercises is free as well. You don't need to enter payment details to sign up.
You can find explanations of many other Python topics by signing up below.