names_vs_boxes
Traditionally in programming languages such as Java or C, variables are boxes which contain values. In C, you can define a variable x
and give it the value 5
.
Behind the scenes, some memory (RAM) in your computer is spared for this new number 5. C knows how much space an integer would take in memory, so this is what happens:
- C spares some memory space equal to the amount needed for an integer.
- C places the value of
5
in the memory spared. - C knows that the variable
x
is located in that memory space.
Python is different.
In Python, when you declare a variable such as x = 5
, it is the value 5
that is created. The variable x
is a name for that existing value.
Seems similar, but there's a key difference! Read on...
Although at this point in our journey it may seem irrelevant, variables in Python are more akin to tags or names than they are to boxes.
Names vs. Boxes
As a way to help you understand the difference between our names and boxes analogy, here's two variables in Python:
age = 30
friend_age = 30
In Python, both age
and friend_age
are actually the same thing. The number 30
is created in the first line, and when it is used again in the second line Python knows to not create it again, since it already exists.
If you change one, the other changes too. If we define those variables in C:
int age = 30;
int friend_age = 30;
Those variables are two different things. That means that takes up approximately double the amount of RAM in your computer, and also it means that if you change one, the other does not change.
Here's a diagram for both:
The equal sign
Because of the way variables behave in Python, the equal sign means something different than it does in Java or C. In Java or C, the equal sign equates to change of the underlying memory.
If you have this in C:
int age = 30;
age = 40;
In the first line, the integer 30
is stored in memory. The variable age
is the location in memory where it is stored.
In the second line, the location in memory remains the same but the contents of the integer is now 40
. We would say that 30
was modified into 40
.
However Python behaves differently. Look at this code:
age = 30
age = 40
In the first line, the number 30
is created and stored in memory. The age
name is what we call a reference to that 30
.
In the second line, the number 40
is created and stored in memory. The age
name is now a reference to that 40
.
When the second line runs, Python realises that there are no variables referencing 30
. Python will then go and remove 30
from memory, since it is no longer used.
Can you change the value of a variable?
What we've looked at so far is that no matter what you do with integers, new ones are created all the time and old ones deleted. We never change integers in Python.
The same goes for strings—you can never modify strings.
Over the rest of this course we'll learn about things that you can modify and behave a little differently. Don't worry too much about it for now though!