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.

Python loads when you run a cell Shift+Enter runs a cell. Cells share variables, like a notebook.

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:

  1. It creates (or finds) an int object with the value 10 somewhere in the heap.
  2. It binds the name my_var to that object, so the name now refers to the object’s memory address.
NAMES (namespace) HEAP (objects) my_var greeting 0x7f3a…a50 · int10 0x7f3a…e30 · str'Hello'
A variable is an entry in a namespace that points at an object. The object carries the value and the type.

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.

Why care about addresses?

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), and hex() formats it.