Variables - Java vs. Python
In Java, a variable is some space reserved in memory, and has a type, a name, and a value assigned to it.
This is NOT how you should think of variables in Python. Variables in Python are more like Java variables that point to object references. More specifically, they point to some object in the heap (dynamic memory allocation).
Recall that, except for Java primitive types, you would usually initialise a new variable in Java with the new
keyword, e.g. String text = new String("hey")
. In this case, a variable stores as its value the address of the object it is pointing to in the memory heap. A variable is also statically bound to be of a certain type at compile time.
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 basic data types and None
). That’s it.
Unlike in Java, a variable does not even have a type. It simply points to an object (which has a type!)
Like Java, Python also runs automatic garbage collection, so there is no need to worry about deallocating memory.