Back to Course
Python Essentials: The Engineering Approach
Module 2 of 20
2. Python Under the Hood
To be an expert, you must understand the tool.
1. Everything is an Object
In languages like C, a variable can store a raw integer value directly in a memory address. In Python, everything—integers, strings, functions—is an Object.
- Header: Contains metadata (Reference Count, Type Pointer).
- Value: The actual data.
2. The Id Function (Memory Address)
You can see where an object literally lives in your RAM using id().
pythonx = 10 print(hex(id(x))) # 0x100a4... (Memory Address)
3. Variables are Labels, Not Boxes
This is the most critical concept to unlearn from other languages.
- Mental Model C++: A variable is a box.
int a = 10puts 10 into box 'a'. - Mental Model Python: A variable is a Name Tag.
a = 10sticks the tag 'a' onto the object 10.
pythona = [1, 2, 3] b = a
We did not copy the list. We just put a second sticker (b) on the same object.
4. Mutability (The Source of Bugs)
- Immutable (Safe): Strings, Tuples, Integers. You cannot change the object content. modifying it creates a new object.
- Mutable (Dangerous): Lists, Dictionaries. You change the object in place.
pythondef append_item(lst): lst.append(99) # This modifies the ORIGINAL list outside the function! my_list = [1] append_item(my_list) print(my_list) # [1, 99] <- Side Effect!
Engineering Rule: Prefer Immutability to avoid side-effects.