Python Memory Mechanics and Variable Scope
Variables as Labels
Variables Are Labels, Not Boxes
Many introductions to programming describe variables as boxes where you store data. You put the number 10 into the 'x' box. This is a helpful starting point, but it's not quite how Python works. A more accurate way to think of a variable is as a label or a tag that you attach to a piece of data.
Imagine you're at an airport baggage claim. The piece of luggage is the data object, like the number 100 or the text "hello". A variable is the luggage tag you stick on it. The tag has a name, like my_number, but the actual object is the suitcase itself. The tag simply points to the suitcase; it doesn't contain it.
my_number = 100
# The name 'my_number' is now a label
# attached to the integer object 100.
One Object, Many Names
What happens if you put a second luggage tag on the same suitcase? Both tags point to the same bag. The same is true in Python. You can attach multiple variable labels to the very same data object.
Let's create one object, the number 500. We'll attach the label price to it. Then, we'll create a new variable cost and set it equal to price. We haven't created a new number. We've just attached a second label, cost, to the exact same 500 object that price is already pointing to.
price = 500
cost = price
# Both 'price' and 'cost' now refer to the same object.
How can we prove this? Python gives us a special tool to peek behind the curtain. Every object in memory has a unique identification number, like a serial number. You can see this number using the built-in id() function.
price = 500
cost = price
print(id(price))
print(id(cost))
# The output will be two identical numbers, proving
# that both variables point to the same memory location.
Because price and cost point to the same object, their IDs are identical. We haven't copied the value; we've just added another name for it. This process of associating a name with an object is called in Python.
Key Idea: Variables are names bound to objects, not boxes containing values.
This might seem like a small detail, but understanding variables as labels is fundamental. It explains many of Python's behaviors, especially when you start working with more complex data types like lists and dictionaries.