Python Lists
append, extend, slicing, and shallow vs deep copy
40 min · interactive lesson with runnable code and 8 graded exercises.
What you'll be able to do
- Explain append vs extend (and += vs +)
- Slice lists confidently, including negative and reversed slices
- Explain shallow vs deep copy with a nested-list example
- Know which list operations are O(1) and which are O(n)
What is a list?
Ordered, mutable collections
A list is an ordered, mutable collection of items. Coming from JavaScript? It's the Python version of an array — but with more powerful slicing.
- Ordered — items keep their position
- Mutable — change, add, and remove items
- Heterogeneous — can mix types
- Indexed — 0, 1, … and -1 for the last item
Three ways to create a list:
append vs extend
The classic interview question
append(x) adds one element to the end. extend(iterable) adds each item from an iterable. The difference shows up the moment you pass a list:
extend works with any iterable — including strings, which unpack into characters:
+= and + look alike, but only one changes the list in place:
Mutation methods & cost
insert, remove, pop — and why some are slow
A Python list is a dynamic array: items sit side by side in memory. Adding or removing at the end is cheap. Doing it at the front forces every other item to shift. Try it — watch the shifted items light up:
Does it matter in practice? Run this race between list.pop(0) and deque.popleft():
Indexing & slicing
start:stop:step
Indexing reads or updates one item. Unlike strings, lists let you assign by index:
Slicing works exactly as with strings — start included, stop excluded — and returns a new list. Notice that out-of-range slices never raise:
Lists also support slice assignment — replace a whole range in one go (the sizes don't have to match):
Assignment is not a copy
Two names, one list
In Python, a variable is a name pointing at an object. b = a doesn't copy anything — it makes a second name for the same list:
Shallow vs deep copy
The interview favorite
A shallow copy creates a new outer list, but the items inside are the same objects. For a flat list of numbers or strings that's all you need. With nested lists, the inner lists are still shared. Try each copy mode below, then mutate b:
Four ways to make a shallow copy — all equivalent:
Common pitfalls
Spot the bug