In this lesson, you’ll learn the fundamental differences between variables in C and Python. Technically, Python has names rather than variables, but you can still use the term variable. That’s an important distinction when you’re dealing with memory in Python.
Variables in C vs Python
Earlier in this course, you saw how you could declare and initialize an integer variable in C. As I mentioned earlier, three things happen under the hood: C allocates enough memory for an integer, it assigns the value 2337 to that space in memory, and then indicates that
x points to that space in memory. In diagram form, that might look something like this.
In fact, Python doesn’t even technically have variables. It has what’s called names. This is a pedantic point, and you should never find yourself in any trouble for calling a Python name “a variable,” but it’s a distinction that’s important to make when dealing with memory in Python. Here’s a line of Python code that assigns the name
x to the value 2337.
What’s really going on under the hood is a little bit more complex than with C. That’s because the standard interpreter for Python is written in C and so all the Python code we write eventually is represented as if we wrote it in C. First, the CPython interpreter, which is the standard interpreter written in C, will create what’s called a
PyObject in memory.
This shows that the Python name
x doesn’t actually own any space in memory with a value. It merely references a space in memory called a
PyObject, and somewhere in that
PyObject is the actual value.
But because every type in Python inherits from
object, then every type ends up mapping to a
PyObject under the hood, whether it’s a string, an
int, or something like your own type, defined with a class.
This tells the garbage collector that it can safely free the memory, or in other words, delete the original
PyObject. If this were a mutable type, like a
list, we wouldn’t see this
PyObject duplication happen.
This is because the is operator checks to see if two names point to the same memory address, or the same
PyObject. The integer type is still immutable, so changing
y would still force Python to create a new
PyObject to point
The big idea is this: in Python, we don’t technically assign variables, even if that’s the terminology we often use. Instead, we bind names to spaces in memory called
PyObjects. Modifying a mutable type will allow the value at that memory space to change, but modifying an immutable type will require a new space in memory, and then the name’s pointer will have to change so that it points to the new
Become a Member to join the conversation.