Variables and Memory · Lecture 01 · 8 min
Variables are Memory References
A Python variable doesn't hold a value. It's a name that points to an object stored somewhere in memory.
Memory, objects and names
When your program runs, Python stores data in a region of memory called the heap. Every piece of data, whether the integer 10, the string 'Hello' or a list, is an object sitting at some address in that heap.
When you write
my_var = 10
Python does two things:
- It creates (or finds) an
intobject with the value10somewhere in the heap. - It binds the name
my_varto that object, so the name now refers to the object’s memory address.
So strictly speaking, my_var is not equal to 10. my_var is a reference to an int object whose value is 10.
Looking at the address with id()
The built-in id() returns a unique identifier for an object during its lifetime. In CPython that identifier is the object’s memory address, given as a base-10 integer. hex() makes it easier to read:
my_var = 10
print('my_var =', my_var)
print('address (decimal):', id(my_var))
print('address (hex): ', hex(id(my_var)))greeting = 'Hello'
print('greeting =', greeting)
print('address (hex):', hex(id(greeting)))The two names point to two different objects, so the addresses differ. The exact numbers change from run to run and machine to machine, so don’t rely on them. What matters is comparing addresses with each other.
You will rarely need id() in real code. In this section we use it as a microscope: watching addresses is the clearest way to see when Python creates a new object and when it reuses an existing one.
Try it: change greeting to some other text in the cell above and run it again. Do you get a new address?
Key takeaways
- Data lives in objects on the heap. Each object has an address, a type and a value.
- A variable is a name bound to an object. It does not contain the value itself.
id(obj)gives the object’s identity (its memory address in CPython), andhex()formats it.