Variables in Python

This is the second of a series of Python lessons. The aim of this series is to help provide an avenue for me to record what I know so far about this amazing language.

So what is a variable in Python?

A variable is simply a location in memory.

For people coming from other languages, you might think this simple definition holds true enough in Python. However, in Python, a variable is a pointer to an object (and it’s memory location). Remember that in this language, everything is an object. A string, a number, an expression, a function, another string, another number, and another string again – all unique objects! Understanding this concept is the foundation to understanding Python and it’s OOP model. Let’s examine the code below:

string = "this is a string"

Looking at this, one might think that the string above refers to a location in memory. If that’s the reasoning, then this code below:

string = "this has been edited"

would mean that the string would refer to the same memory location, only this time, it has been reassigned and thus has a different value. This is not the case in Python. Let’s use the built-in id method to verify this.

The id function in Python returns the identity – the memory address – of an object. Loosely, it refers to the location in memory of the said object. Let’s try this:

In [1]:
string = "this is a string"
In [2]:
string = "string edited"
 I am using the amazing iPython Notebook. You should try it out. I digress.
So, from the demo above, we see that even though the variable string is one and same variable, the id changes when it’s value changes. This is exactly the binding model of Python. It means that python binds variable names to objects, in this case “this is a string”, or “string edited”. Because both values are different, they are two different objects, with different memory locations, even though they are bound to same variable string. What happens is that when the string was reassigned, Python removed the binding of string from “this is a string” to “string edited”, meaning the first (“this is a string”) can exist unbound on it’s own.
To summarize, python binds variable names to objects. It is these bound objects that have a location in memory, not the variable names; the variable names merely point to the particular bound objects.