Lesson 4 of 16 · 52 min · UG / professional
Names, objects and shared references
gross is a label. 48000 is an object. Two names can point at the same list — then append in one place surprises the other. == asks ‘same contents?’; identity asks ‘same object?’
Labelled school bag
Variables are named pockets.
You will be able to
- ✓ Treat a name as a label on an object
- ✓ Know two names can share one list
- ✓ Distinguish ‘same contents’ from ‘same object’ as a policy
Types live on objects, not on names
gross = 48000 sticks the label gross on an integer object. Later gross = "48000" rebinds the name to a string object. The name did not ‘change type’; it now points at a different object. That is dynamic typing — fast, and easy to mix WhatsApp text with rupees.
When you no longer have a name for an object, the engine can reclaim it (garbage collection). You rarely call that yourself. You do need to not keep huge lists alive in a global ‘just in case’.
Shared references
a = [10, 20]; b = a does not copy the tray. append through b is visible through a. That surprise is how two functions ‘helpfully’ edit the same attendance list. If you needed a snapshot, build a new list (loop + append here; copy on a laptop).
Equality of contents (==) is ‘do these look the same?’. Identity is ‘are these the same object?’. Campus policy: compare rolls with ==. Do not assume two dicts with the same fields are the same object in memory.
Laptop: is vs ==
a = [10, 20] b = a c = [10, 20] print(a == c, a is b, a is c)
Words that matter
- Reference
- A name pointing at an object.
- Rebind
- Point a name at a different object (new assignment).
- Identity
- Same object in memory — ‘is’ on a laptop.
Common mistakes
Avoid: b = a on a list, then wondering why a changed.
Do this: Build a new list when you need a snapshot.
Run it step by step
Each box is a real program. Press Run, change a number, Run again — the output must follow your code.
1. Step 1 — rebind a name
gross moves from 48000 to 52000. One label, new object.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
2. Step 2 — a snapshot is a new list
Copy by walking. Changing the copy must not change morning.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Example program — Shared vs copied
same is one list two names. copy is a second tray.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Your turn — Rebind CTC
Start with 50000. Subtract 2000. Print so 48000 appears.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Self-assessment
Check your understanding before you mark the lesson complete.
Progress is stored in a browser cookie on this device.