1. Everything is an Object
- Every value is an object; variables are names bound to objects (reference semantics), not boxes.
id(x)+istest identity;==tests equality (calls__eq__).- Assignment
a = baliases — both names point to the same object.
a = [1, 2]
b = a # same list object
b.append(3)
print(a) # [1, 2, 3] — b is not a copy
2. Immutable vs Mutable
| Immutable | Mutable |
|---|---|
int, float, bool, str, bytes, tuple, frozenset | list, dict, set, custom objects |
| Hashable | Not hashable (list/dict/set) |
| Safe as dict keys | must not be dict keys |
- Tuple with a list inside is still “unhashable” in spirit — immutable reference but mutable inner object.
t = ([1],); t[0][0]=9works.
Interview trap: tuple is immutable as a container, but a hashing its contents failing is a classic — hash((1, [2])) → TypeError.
3. Interning & small-int caching
- Small integers
-5..256are pre-created, singletons —a = 257; b = 257; a is bis implementation-defined, usuallyFalse. - CPython constant folding may merge ints in the same code unit.
- String interning for simple identifiers can make
"hello" is "hello"True. - Never rely on
isfor numbers/strings — use==.
4. Operators & the truthiness trap
- Truthiness (not strict boolean):
0,0.0,"",[],{},set(),Noneare falsy; everything else truthy. bool(x)calls__len__for containers, otherwise__bool__./vs//:/gives float;//floor-divides (ints → int).-7 // 2=-4(floor, not truncation!).%sign follows the divisor.==chaining:1 < x < 5is chained comparison — Python expands it to1 < x and x < 5.isvs==again: objects equal by content (==) need not be identical (is).
5 / 2 # 2.5
5 // 2 # 2
-7 // 2 # -4 (floor, not truncation)
-7 % 3 # 2 (sign follows divisor)
1 < 3 < 5 # True (chained)
5. The memory/object model pytricks
copyvs deepcopy:copy.copyshallow — new outer container, shared contents;copy.deepcopy— full copy recursively.- Identical immutable values can share memory freely (safe), mutable values never automatically share copy semantics.
sys.getrefcount(x)shows reference count — never manage it manually.Noneis a singleton — the proper way to compare to None isis None, not== None.
6. The classic intern questions
==vsis— equality of value vs identity of object.[] == []True,[] is []False.a is None— the canonical None check.- Mutable default —
def f(x=[])is evaluated once → shared default across calls (see Part 2). - String/bytes confusion —
stris immutable Unicode;bytesimmutable byte sequence. - Integer division —
/vs//semantics, including negatives and floor behaviour.
Premium Content
Unlock Part 1: Types, Objects & Memory and all premium lessons with a subscription.
All premium lessons
Ad-free experience
Priority support
From ₹199.99/year — See plans