Skip to content

Latest commit

Β 

History

History
560 lines (364 loc) Β· 9.13 KB

File metadata and controls

560 lines (364 loc) Β· 9.13 KB

🐍 PYTHON β€” LEVEL 1 NOTES: VARIABLES MODEL


πŸ”· 1. WHAT IS A VARIABLE?

🧠 Mental Model

A variable is a label (reference) pointing to an object in memory


NOT a Container

❌ Variables do NOT store values inside them βœ… Variables REFERENCE objects that store values


🧠 Visualization

Variable (Stack)     Object (Heap)
    x  ─────────────► [10]

πŸ”· 2. CORE PRINCIPLE

❗ Everything in Python is an object

  • int β†’ object
  • str β†’ object
  • list β†’ object
  • function β†’ object
  • module β†’ object

All objects are stored in HEAP

Variables are just labels pointing to heap objects


πŸ”· 3. ASSIGNMENT BEHAVIOR

🧠 Rule: Assignment Copies REFERENCE, NOT Object


Example 1: Mutable Assignment

a = [1, 2]
b = a
a ─┐
   β”œβ”€β”€β–Ί [1, 2]  (one object in heap)
b β”€β”˜

Both point to SAME object


Example 2: Immutable Assignment

x = 10
y = x
x ─┐
   β”œβ”€β”€β–Ί [10]    (immutable, typically same object due to caching)
y β”€β”˜

Reference copied, not value


πŸ”· 4. MUTABLE vs IMMUTABLE BEHAVIOR


πŸ”Ή Mutable Objects

list, dict, set

Property:

❗ Modifications change the SAME object


Example

x = [1, 2]
y = x
y.append(3)
print(x)  # [1, 2, 3]  ← x also changed!
Before: x ─┐
           β”œβ”€β”€β–Ί [1, 2]
        y β”€β”˜

After:  x ─┐
           β”œβ”€β”€β–Ί [1, 2, 3]  ← SAME object modified
        y β”€β”˜

πŸ”Ή Immutable Objects

int, float, str, tuple

Property:

❗ Any modification creates NEW object


Example

x = 10
y = x
y = y + 1  # or y += 1
print(x)   # 10  ← x unchanged
print(y)   # 11
Before: x ─────► [10]
        y β”€β”€β”€β”€β”€β”˜

After:  x ─────► [10]        (original, unchanged)
        y ─────► [11]        (new object created)

πŸ”· 5. MUTATION vs REBINDING


πŸ”Ή Mutation

Changes the object itself

x = [1, 2]
x.append(3)  # ← mutation
x ─────► [1, 2, 3]
         (same object, modified)

πŸ”Ή Rebinding

Points to a different object

x = [1, 2]
x = [3, 4]  # ← rebinding
Before: x ─────► [1, 2]
After:  x ─────► [3, 4]  (new object)

🧠 CRITICAL DIFFERENCE

Action Mutable Immutable
Mutation Same object N/A
Rebinding New reference New object

πŸ”· 6. FUNCTION ARGUMENTS (CALL-BY-SHARING)


🧠 Python uses: Call-by-sharing

Function parameter receives a REFERENCE to the same object


Case 1: Mutation (Affects Original)

def modify(lst):
    lst.append(10)  # mutation

a = [1, 2]
modify(a)
print(a)  # [1, 2, 10]  ← changed!
Inside function:
lst ─┐
     β”œβ”€β”€β–Ί [1, 2, 10]  ← SAME object modified
a β”€β”˜

Case 2: Rebinding (Local Only)

def modify(lst):
    lst = [999]  # rebinding

a = [1, 2]
modify(a)
print(a)  # [1, 2]  ← unchanged!
Inside function:
lst ─────► [999]  (new local object, function scope only)
a ─────► [1, 2]   (unchanged, still original)

πŸ”· 7. IDENTITY vs EQUALITY


a is b   # β†’ Are they the SAME object? (identity)
a == b   # β†’ Do they have the SAME value? (equality)

🧠 Key Difference

is β†’ Identity Check

  • Checks if both variables point to same object in memory
  • Compares memory addresses
a = [1, 2]
b = a
print(a is b)  # True  (same object)

== β†’ Equality Check

  • Checks if both objects have same value
  • Compares content
a = [1, 2]
c = [1, 2]
print(a == c)  # True  (same value)
print(a is c)  # False (different objects)

🧠 Table

a = [1, 2]
b = a
c = [1, 2]
Expression Result Why
a is b True Same object in memory
a == b True Same content
a is c False Different objects
a == c True Same content

πŸ”· 8. COPY vs REFERENCE


πŸ”Ή Reference Copy

b = a
  • Creates new variable
  • Points to SAME object
  • Both see mutations
a ─┐
   β”œβ”€β”€β–Ί [1, 2]
b β”€β”˜

πŸ”Ή Shallow Copy

b = a[:]  # or b = a.copy()
  • Creates NEW object
  • Copies content at top level
  • Mutations don't affect original
a ─────► [1, 2]
b ─────► [1, 2]  (different object, same content)

πŸ”· 9. STEP-BY-STEP MENTAL MODEL


When analyzing code:


🧠 Step 1: Variables are references

  • Track which variable points where
  • Not "what value does x hold" but "what object does x refer to"

🧠 Step 2: Identify object type

  • Mutable? (list, dict, set)
  • Immutable? (int, str, tuple)

🧠 Step 3: Identify operation

  • Mutation: x.append(), x[0] = val, x.pop()
  • Rebinding: x = new_value

🧠 Step 4: Apply rules

  • Mutable + mutation β†’ shared object changes
  • Immutable + rebinding β†’ new object created
  • Function argument β†’ reference passed, mutation affects original

πŸ”· 10. COMMON MISTAKES


❌ Mistake 1: "Variables store values"

x = 10  # ❌ "x stores 10"

βœ”οΈ Correct: "x is a reference to object 10"


❌ Mistake 2: "Assignment copies the object"

b = a  # ❌ "copied a to b"

βœ”οΈ Correct: "b now references the same object as a"


❌ Mistake 3: "Functions pass by reference"

βœ”οΈ Correct: "Functions use call-by-sharing (reference passed)"


❌ Mistake 4: "x += always mutates"

x = [1]
x += [2]  # βœ”οΈ Mutates (in-place for lists)

y = 10
y += 5    # ❌ Does NOT mutate (creates new int)

βœ”οΈ Correct: "Immutable objects create new object, mutable objects may mutate in-place"


πŸ”· 11. FINAL MENTAL MODEL (5 GOLDEN RULES)


🧠 Master These 5 Rules

  1. Everything is an object β†’ stored in heap
  2. Variables are references β†’ labels pointing to objects
  3. Assignment = reference copy β†’ both point to same object
  4. Mutable objects β†’ mutation changes shared object
  5. Immutable objects β†’ reassignment creates new object

🎯 HOW TO THINK IN INTERVIEW


Process:

1️⃣ Draw boxes for objects in heap
2️⃣ Draw arrows for references (variables)
3️⃣ Identify mutable vs immutable
4️⃣ Track mutation vs rebinding
5️⃣ Follow function flow
6️⃣ Predict output

πŸš€ LEVEL 1 MASTERY GOALS

By end of Level 1, you should:

βœ… Instantly recognize reference behavior βœ… Explain mutation vs reassignment clearly βœ… Predict output without running code βœ… Distinguish is from == βœ… Handle function arguments confidently


Ready to test? Go to assignement/test folder!

Next Level: Level 2 = nested structures, default arguments, integer caching, string interning, deep copy


Level 2

Mental Model

Names bind to objects. Assignment rebinds names; mutation changes objects. Keep these two operations separate in your mind.

Solve Steps

  1. Draw name -> object bindings after each line.
  2. Mark object as mutable or immutable.
  3. Track aliasing when multiple names point to one object.
  4. For functions, treat arguments as new local names bound to passed objects.

Level 3

Mental Model

Scope and binding time are key: LEGB lookup, closure capture, and default-argument evaluation can preserve unexpected state.

Solve Steps

  1. Resolve each variable by LEGB.
  2. For closures in loops, test late binding assumptions.
  3. Check whether defaults are evaluated once at function definition.
  4. Fix with explicit rebinding or immutable defaults when needed.

Level 2 Questions

  1. After a=[1,2]; b=a; b.append(3), why does a change?
  2. In a function, what differs between x.append(1) and x=[1]?
  3. Why can two variables have equal values but different identities?

Level 3 Questions

  1. How does late binding in closures create surprising loop behavior?
  2. Why are mutable default arguments a state-retention trap?
  3. Which LEGB step do you check first when debugging shadowed variables?

πŸ”· 2. EXECUTION MODEL

Understand how this topic runs in actual program flow:

  • Read statement
  • Resolve type/object/reference
  • Execute operation (assignment, mutation, call, return)
  • Update memory state (stack/heap bindings)
  • Re-check final output from updated state

πŸ”· 3. INTERVIEW MENTAL MODEL (STEP-BY-STEP)

When you see ANY question:


🧠 Step 1: Identify variable type

  • Primitive? β†’ value
  • Object? β†’ reference

🧠 Step 2: Where is it stored?

  • Primitive β†’ stack
  • Object β†’ heap (via reference)

🧠 Step 3: Assignment behavior

  • Primitive β†’ copy value
  • Object β†’ copy reference

🧠 Step 4: Operation type

  • Field change β†’ mutation
  • new β†’ new object (reassignment)

🧠 Step 5: Function call

  • Always pass-by-value
  • Object β†’ reference copied