Lesson 1 of 4Module 1 · 0% of course
‹ PrevNext ›
Python Foundations · Names & data

Python properly, part 1: name tags, mutability, dicts & money

Variables are name tags on objects, not boxes. Why that matters for lists, default args, fast dict lookups, and why floats break money. Ends with a trade reconciler.

35 min · 8 steps · videoJump to quiz ↓
Programming Terms: Mutable vs Immutable Corey Schafer · 7 min
Open in YouTube
Step 1 of 8 · 1. Names are tags, not boxes35 min read ·

1. Names are tags, not boxes

In Python, x = [1, 2, 3] creates a list object and sticks the name tag x on it. y = x does not copy anything; it sticks a second tag on the same object.

x = [1, 2, 3]; y = x; y.append(4)xy[1, 2, 3, 4]ONE list object (id 0x7f…)Two name tags, one object → print(x) shows the 4
Aliasing: x and y point at one list. Mutating through y is visible through x.
x = [1, 2, 3]
y = x
y.append(4)
print(x)        # [1, 2, 3, 4]
print(x is y)   # True  (same object)
z = x.copy()    # or list(x) / x[:] → a real copy
print(z is x)   # False
Next: 2. Mutable vs immutable

Review cards

  • What does `y = x` do for a list: copy or second name?

    second name, same object

  • Why is dict lookup fast?

    hash table: hashes key straight to a slot, ~O(1) vs scanning a list O(n)

  • Why not use floats for money?

    binary floats can't represent 0.1 exactly; use Decimal or integer cents

  • What's wrong with `def f(x, book=[])`?

    default list is created once and shared across calls; use None

‹ PrevNext ›