If you think x = 10 means “x stores 10”… you are already misunderstanding Python.

Today, we fix that.


Today’s Goal

By the end of today, you will:

  • Understand how Python stores data in memory
  • Learn references vs values
  • Understand mutability
  • Avoid hidden bugs

The Illusion

You write:

x = 10
y = x

You think:

x and y both store 10

Wrong.


What Actually Happens

Memory:
[10]  ← object

x ─────┐
       ├──→ [10]
y ─────┘

Variables do not store values. They store references to objects.


Key Rule

Everything in Python is an object.


Identity vs Value

x = 10
y = 10

print(x == y)
print(x is y)
  • == compares values
  • is compares memory identity

Important Note

Python may reuse objects (interning), especially for small integers.


Mutability (Critical Concept)

Immutable Example

x = 10
y = x

x = x + 5
x → [15]
y → [10]

A new object is created.


Mutable Example

a = [1, 2, 3]
b = a

a.append(4)
a ───→ [1,2,3,4]
b ───→ [1,2,3,4]

Same object is modified.


Why This Matters

Mutable objects:

  • change in place
  • affect all references

Immutable objects:

  • create new objects
  • safer but can be slower

Function Behavior

def add_item(lst):
    lst.append(100)

my_list = [1, 2, 3]
add_item(my_list)

print(my_list)

Output:

[1, 2, 3, 100]

Because the same object is modified.


Common Trap

a = [1, 2, 3]
b = a

This is NOT a copy.


Correct Copy

b = a.copy()

Under the Hood

Each object has:

  • Type
  • Value
  • Reference count

Reference Counting

Object: [1,2,3]
Ref count: 2 (a, b)

When reference count becomes 0, Python frees the memory.


Inspect Identity

a = [1,2,3]
b = a

print(id(a))
print(id(b))

Same ID means same object.


Mutable Default Argument Trap

def add_item(item, lst=[]):
    lst.append(item)
    return lst
add_item(1)
add_item(2)

Output:

[1]
[1, 2]

Why This Happens

Default arguments are evaluated once.


Fix

def add_item(item, lst=None):
    if lst is None:
        lst = []
    lst.append(item)
    return lst

Memory Model Summary

  • Variables are references
  • Objects live in memory
  • Mutability defines behavior
  • Reference count controls lifetime

Your Task

  • Use id() and is
  • Compare mutable vs immutable behavior
  • Modify objects and observe results

Common Mistakes

  • Treating variables as value holders
  • Ignoring mutability
  • Accidentally sharing objects
  • Misusing assignment instead of copying

Think Deeper

  1. Why are strings immutable?
  2. Why are lists mutable?
  3. What happens when reference count becomes zero?

Final Insight

Variables are labels pointing to objects in memory.


Tomorrow

Lists, Tuples, Sets — internals and complexity


Rule

  • Think in memory
  • Think in references
  • Not in variables

See you in Day 3.