Python · Module 04: Built-In Data StructuresTutorial 9 of 30

4.1 Lists, Slicing, Methods & Shallow vs. Deep Copy

Master Python's workhorse collection: how lists work in memory, indexing & slicing, append vs extend, sort vs sorted, and the famous Shallow vs. Deep Copy bug.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. What Is a Python list? (The Expandable Shopping Cart Analogy)

Think of a Python list as a numbered shopping cart that automatically grows whenever you toss in more items:

  • Ordered: Items stay in the exact order you put them in.
  • Mutable: Unlike strings, you can change, add, or delete items in place!
  • Dynamic: Can grow/shrink anytime and even hold mixed types (["tea", 42, True]).
Visual: Inside a Python `list` — Dynamic Array of Object Pointers with Spare Capacity
[0]"tea"[1]"milk"[2]"eggs"[3]42[4]spare[5]spare✓ items.append("bread") & items.pop() use spare end slots → Instant O(1)!✗ items.insert(0, x) or items.pop(0) shifts EVERY item right/left → Slow O(N)!Notice: A Python list can even mix types ("tea" and 42) because each slot holds a reference!
PYTHON
cart = ["tea", "milk", "eggs"]

cart[1] = "oat milk"       # ✓ Mutate in-place!
cart.append("bread")       # Add to end -> O(1) fast!
last = cart.pop()          # Remove & return last item -> O(1) fast!

print(cart)                # ['tea', 'oat milk', 'eggs']
print("Removed:", last)    # Removed: bread

2. Essential List Methods & Two Classic Beginner Traps

MethodExampleWhat It DoesSpeed
.append(x)a.append(4)Adds one single item x to the endO(1)
.extend(iter)a.extend([4, 5])Unpacks and adds each item from another listO(k)
.insert(i, x)a.insert(0, 99)Inserts at index i (shifts items right)O(N)
.pop(i)a.pop() / a.pop(0)Removes & returns item (default: last)O(1) end / O(N) front
.remove(x)a.remove("tea")Removes first matching value xO(N)
.sort()a.sort()Sorts in-place and returns None!O(N log N)
sorted(a)b = sorted(a)Returns a brand-new sorted list (a unchanged)O(N log N)

Trap #1: append() vs. extend()

PYTHON
nums = [1, 2]
nums.append([3, 4])   # [1, 2, [3, 4]]  ← Nested list!
nums = [1, 2]
nums.extend([3, 4])   # [1, 2, 3, 4]    ← Flat list!

Trap #2: x = nums.sort() Sets x to None!

PYTHON
nums = [3, 1, 2]
wrong = nums.sort()      # ✗ wrong is None! (nums itself was sorted in-place)
right = sorted(nums)     # ✓ right is [1, 2, 3]

3. The #1 Python Memory Trap: Alias vs. Shallow Copy vs. Deep Copy

Remember Module 1.2 (Variables are sticky-note labels)? Watch what happens when you write b = a on a list:

PYTHON
a = [10, 20, 30]
b = a              # NOT a copy! Both 'a' and 'b' point to the SAME list!
b.append(99)
print(a)           # [10, 20, 30, 99]  ← Surprise! 'a' changed too!

Now look at all 3 levels of copying when you have nested lists (like a 2D grid):

Visual: Assignment (`b = a`) vs. Shallow Copy (`a.copy()`) vs. Deep Copy (`deepcopy(a)`)
1. b = a (Alias!)ab[[1, 2], [3, 4]]Editing b mutates a too!2. b = a.copy() (Shallow)a outerb outershared [1, 2]Safe for 1D; inner lists shared!3. deepcopy(a) (100% Safe)a outerb outer[1, 2][1, 2]Completely independent clones!
PYTHON
import copy

grid = [[1, 2], [3, 4]]

shallow = grid.copy()        # Or grid[:] — fine for 1D lists, shares inner lists!
deep    = copy.deepcopy(grid) # Completely independent clone at every nesting level!

deep[0][0] = 999
print(grid[0][0])            # 1 (Safe! Original untouched!)

4. Interactive Trace: Mutating a List Step-by-Step

Tracing List Mutation, Slicing & Copying
Interactive Line-by-Line Execution Trace · Step 1 of 5
1→nums = [10, 20, 30]
2copy_nums = nums.copy()
3nums.append(40)
4removed = nums.pop(0)
5print(nums, copy_nums)
Variables in Memory
nums[10, 20, 30]list
Console Output
(nothing printed yet)
What just happened: Creates a mutable list object [10, 20, 30] in memory.

Quick Quiz: Module 4.1 — Lists & Copying

Q1.What does this snippet print?
a = [3, 1, 2]
b = a.sort()
print(b)
Q2.What does this snippet print?
x = [1, 2]
y = x
y.append(3)
print(x)
Q3.Which operation is O(1) fast on a Python list?

Keep Exploring: Related Lessons & Tools

All Courses →