Lecture Notes — Lecture 11: Lists and Slicing

Companion to the lecture plan and the worked examples. Read the Definitions before class, the Explanation after it; the practice questions and the lecture quiz close the loop.

Definitions

Explanation

Assignment binds names; it rarely copies. a = b makes one list with two names. cs-044's grid = [[0]3]2: grid[0][0] = 9 shows up in BOTH rows (aliasing), while the fix [[0]*3 for _ in range(2)] keeps rows independent - the reference prints exactly this pair.

Slices copy; views do not exist. lst[a:b] hands you a new list. There is no live window - which is why cs-043's rotation by slicing is safe while a shared-reference rotation would corrupt.

In-place methods return None. lst.sort() returns None; sorted(lst) returns a new list. Chaining lst = lst.sort() destroys your list - the single most common Block II crash.

Rotation is arithmetic on indices. cs-043: left by 2 on [1,2,3,4,5] is [3,4,5,1,2]; the formula is lst[k:] + lst[:k] (mod len for big k: the reference shows k=7 ≡ k=2). Right rotation is lst[-k:] + lst[:-k].

Deduplicate with intent. cs-042: order-preserving dedupe ([3,1,3,2,1,3] → [3,1,2]) needs a seen-set and appends; sorting first ([1,2,3]) destroys the requested order. Both are 'correct' - the spec picks.

Examples

The lecture's worked examples live in examples.md; the case studies this lecture builds on are worked in class from the projector. The case sequence with difficulties:

Common misconceptions

Summary and key takeaways

  1. Assignment aliases; slices and explicit copies duplicate.
  2. In-place methods return None - do not chain them.
  3. Rotation is index arithmetic: lst[k:] + lst[:k].
  4. Dedupe: order-preserving needs a seen-set; sorting changes the spec.

Practice questions

Where this leads

Next lecture: Debugging Lab: Real Defects. The quiz below checks this lecture's essentials before we build on them.