List Slicing

Context: FIT1008_MOC · Python feature that simplifies block shifts in ArrayList · copy (not view) semantics

Quick Revision

  • 🎯 Objective: lst[a:b] returns a new list of elements [a, b) ➔ on the left of = it overwrites a block in one statement.
  • 📦 Core Components: [a:b:step] stride ➔ slice assignment replaces shift loops.
  • ⚡ Key Constraint: a Python slice copies ( time + space) — NumPy slices are views (aliased).

📝 Core

1. The Slice (Extract / Overwrite a Block)

  • Readlst[a:b] returns a new list of elements a up to (excluding) b; omitting an endpoint defaults to start/end; [a:b:step] adds a stride.
  • Assignment ➔ on the left of = it overwrites a block in one statement ➔ replaces ArrayList’s element-shifting loop.

2. Copy vs View Semantics

  • Python copieslst[a:b] builds a new list of elements ➔ time + space (a shallow copy — element refs shared, not the objects).
  • Hidden cost ➔ slicing inside a loop can hide a cost.
  • NumPy views ➔ return views (no copy, ) sharing the parent buffer ➔ fast but aliased (mutating the view mutates the original).

⚙️ Core Implementation

🔹 Slice reads, reverse, and assignment

⚖️ Core Decision Matrix

Slice useCostNote
lst[a:b] (read) time + spaceshallow copy of elements
lst[a:b] = seqmay shift the tail if lengths differ
replace shift loopone block-copy vs explicit per-element loop
NumPy arr[a:b]view (aliased), not a copy

When It Flips: slicing is concise and often C-optimised (small constant) but allocates — for huge ranges or hot loops, in-place index manipulation avoids the copy.

📊 Exam Execution Trace

Manual Execution Trace

Python copy vs NumPy view:

Step / StatePython list[a:b]NumPy arr[a:b]
0 (Init)
allocates?yes (new list)no (shares buffer)
cost
mutate affects original?noyes (aliased)

Applied Exercise

Problem: Compare slice assignment to a shift loop. Derivation Proof / Hand-Calculation Walkthrough:

Final Extracted Output: same asymptotics — slice assignment is a readability/constant-factor win, not a complexity win.

🧠 Active Recall