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

Variables - C++ vs. Python

In C++, a variable is some space reserved in memory, and has a type, a name, and a value assigned to it.

A C++ variable

This is NOT how you should think of variables in Python. Variables in Python are more like pointers (but without the complications of C++ pointers). They point to some object in the heap (dynamic memory allocation).

Recall that in C++, a pointer is a variable where the value is an address of what it is pointing to. A pointer variable is also statically bound to be of a certain type. For our purposes, we only consider a pointer to be pointing to a location in the memory heap.

A C++ pointer

In Python, a variable is simply a label (or a nickname) that always points to an object in the memory heap (remember, everything is an object in Python, including None). That’s it.

Unlike in C++, a variable does not even have a type. It simply points to an object (which has a type!)

A Python variable

Also, unlike C++, you do not need to worry about having to delete anything. These will automagically be done for you in the background, while you concentrate on things that really matter!