This is an archived version of the course. Please see the latest version of the course.

Python Variables

Remember again that Python variables are simply labels, and are not bound to a specific type.

A variable points to an object

>>> x = 5
>>> print(x)
>>> print(type(x))
>>> y = complex(3, 5)
>>> print(y)
>>> print(type(y))

Like C++ pointers, you can have different variables pointing to the same object.

Multiple variables can point to an object

Use id() to get the address of the object in memory. If two variables have the same id, they both point to the same object.

>>> a = "I love to learn"
>>> print(a)
>>> print(type(a))
>>> b = a
>>> print(b)
>>> print(type(b))
>>> print(id(a))
>>> print(id(b))
>>> print(id("I love to learn"))
>>> a is b    ## This is equivalent to id(a) == id(b)

You can also reassign an existing variable to point to a different object (of any type) at any stage of your program.

Variables can be reassigned to a different object

Try out the following, and make sure you understand what is happening.

>>> x = 10
>>> print(x)
>>> print(type(x))
>>> y = 7.11
>>> print(y)
>>> print(type(y))
>>> x = "I am no longer the number 10"
>>> print(x)
>>> print(type(x))
>>> x = y
>>> print(x)
>>> print(type(x))
>>> y = "Imperial College London"
>>> print(y)
>>> print(type(y))
>>> print(x)
>>> print(type(x))

Remember: a Python variable itself does not have a type. It is just a nickname. It is the object that it is pointing to that has a type.