Lesson · Core Collections
Lists
60 min readLists
Lists are mutable, ordered sequences designed for general-purpose collection work. Their dynamic-array behavior explains why append is cheap on average while insertion near the front is not.
Learning goals
- Trace the worked example line by line and say what the list holds after each call, and what each call returns.
- Distinguish mutation from rebinding:
items.append("c")changes the object, whileitems = items + ["c"]binds a new one. - Use
append,extend, andinsertcorrectly, remembering that all three returnNone. - Choose
poporremovebased on what you need back, and match each to its exception (IndexErrorversusValueError). - Predict when
.copy()protects a list and when shared inner elements still leak changes through both names.
Mental model
Every step has one of two behaviors: readers such as slicing produce new objects, while the mutating methods change the existing list and return None. Copying sits on the boundary between the two, since a new outer list can still share every element with the original, which is where aliasing questions begin.
Reading makes new objects, changing edits this one
a mutating method returns None
Mental model
the same mechanism as a compact list
build the list (literal, comprehension, or constructor) ↓ read: index one element; slice a range (a slice returns a NEW list) ↓ change: append / extend / insert mutate in place and return None ↓ take out: pop(index) returns the item; remove(value) returns None ↓ copy: list.copy() makes a new outer list that shares its elements
Core idea
A list is a mutable, ordered sequence backed by a dynamic array: adding or removing at the end is cheap, and doing either near the front shifts every later element. Two rules keep the semantics straight: mutating methods change the object in place (and return None except for pop), while slicing and copy() create new list objects that may share their inner elements. Most list surprises are identity questions rather than syntax questions, so track which name refers to which object.
Creation
Creation in Lists means constructing a new object with valid initial state. Compare literal syntax, constructors, and factory-style APIs where they exist, and note whether construction copies or reuses existing objects.
Indexing and negative indexing
An index selects one element. Positive indexes count from zero at the front, while negative indexes count backward from the end; an invalid element index raises IndexError.
Slicing
A slice selects a range of a list with items[start:stop:step] and returns a new list, leaving the original untouched. Defaults are start 0, stop len(items), and step 1, the stop index is excluded, and out-of-range bounds are clamped rather than reported.
Mutation
Mutation changes the state of an existing object without rebinding the name that refers to it. In Lists, track object identity before and after the operation to distinguish mutation from replacement.
append, extend, insert
append(x) adds one object, extend(iterable) adds each item from an iterable, and insert(i, x) places one item before an index. All three mutate the list and return None.
remove, pop
remove(value) deletes the first equal value and returns None; pop(index) deletes and returns an element. Their different return values reflect different use cases.
Sorting
list.sort() rearranges the list in place and returns None, while sorted(items) builds and returns a new sorted list. Both accept key= and reverse=, and the elements (or their keys) must support ordering comparisons.
Reversing
list.reverse() reverses the list in place and returns None, while reversed(items) returns a lazy iterator over the elements from the back. The iterator does not copy the list, so it sees mutations made before it is consumed.
Copying
Copying requires you to decide whether a new outer object, new nested objects, or merely another reference is needed. Draw the object graph when nested mutable state makes the answer unclear.
Aliasing
Aliasing occurs when multiple names refer to the same mutable object. A mutation through one alias is visible through the others because there is still only one object.
Nested lists
A nested list stores references to other list objects. Repeating one inner list with multiplication can create aliases, so construct independent rows with a comprehension when independence is required.
Complexity basics
Complexity basics connects Python syntax to algorithmic behavior. Focus on growth with input size, expected versus worst-case behavior, and whether hidden copying or shifting occurs.
Walkthrough
items = ["a", "b"]creates one list object;items.append("c")mutates it to["a", "b", "c"]anditems.extend(["d", "e"])grows it to five elements, and both calls returnNone.items[1] = "B"replaces the element at index 1 ("b") without changing the list's identity, so the object is now["a", "B", "c", "d", "e"].removed = items.pop()takes the last element off the list, leavingremoved = "e"anditemswith four elements;items.copy()then creates a second list object holding the same four elements in the same order.print(copy_of_items is items)printsFalse, becausecopy()made a new list, while a plaincopy_of_items = itemswould have given the same object a second name. Predict before running: the final list contents, the value ofremoved, and the Boolean printed byis.
Experiments to try
- Replace
items.copy()withcopy_of_items = itemsand predict theisresult before running. Restore.copy()afterward and say in one sentence what changed. - Swap
items.pop()foritems.pop(0); predictremovedand the remaining list, then note which pop had to move other elements. - Change
items.extend(["d", "e"])toitems.append(["d", "e"])and predict the list shape. Read the output, then state the difference between adding one object and adding each item. - Call
items.remove("z")and catch theValueError, then callitems[99]and catch theIndexError. Explain which operation searches by value and which addresses by position.
Common mistakes
- Expecting
items.append(["d", "e"])to merge two lists:appendadds its argument as a single element, so the list argument becomes a nested list, whileextendadds the items one by one. - Reading the return value of a mutating method:
append,extend,insert,remove, andsortall returnNone, soitems = items.append("c")leavesitemsbound toNone. - Mixing up
removeandpopfailures:removesearches by value and raisesValueErrorwhen the value is absent, whilepopaddresses by position and raisesIndexErrorwhen the index is out of range. - Assuming
.copy()isolates nested data: it creates a new outer list, but the elements are shared, so mutating a nested list is visible through both copies.
Practice: Easy
- Build
itemsstep by step as in the worked example. After each mutation, printitems,len(items), anditems[-1]; predict all three values at every step before running. - Replace the last print with
copy_of_items == itemsand then withcopy_of_items is items. Predict both Booleans and explain why equality and identity disagree or agree. - Trigger both failure modes on purpose:
items[10]for theIndexErroranditems.remove("missing")for theValueError. Predict which line raises which exception, then confirm.
Practice: Medium
- Rebuild the example using
items += ["d", "e"]instead ofitems.extend(["d", "e"]); show the result is the same, then explain whyitems = items + ["d", "e"]also produces the same contents but binds a new object. - Write the final list as a single literal (
["a", "B", "c", "d"]) and compare: list every example line that mutated the list in place, and name the one line that replaced an element through its index. - Create
rows = [[0, 0]] * 2, mutaterows[0][0] = 1, and observe that both rows change; rebuild the list asrows = [[0, 0] for _ in range(2)]and confirm the rows are now independent.
Practice: Hard
- Design
push(items, value)andpop_last(items)helpers over a list, deciding and documenting the behavior ofpop_last([])before writing the code. Test a push, a pop back to empty, and the empty case. - Build a failure lab with three entries:
new_items = items.append("f")leavingnew_itemsasNone,items.remove("missing")raisingValueError, and the[[0, 0]] * 2aliasing bug. For each entry, record the output and explain it with return values, exceptions, or shared references. - Time three workloads on a 1,000-element list: appending,
insert(0, item), andpop(0)versuspop(), usingtimeitover enough repetitions to see a stable ratio. Report the numbers and explain the gap with the shifting that happens near the front of a dynamic array.
Lesson checklist
- I can trace the worked example and state the list contents and each call's return value after every line.
- I can say which list operations mutate in place and which create new objects, including
.copy(). - I can choose between
removeandpopfrom what I need back, and predict each one's exception. - I can explain the
[[0, 0]] * 2trap and build independent rows instead.
Remember
A list is a mutable, ordered sequence backed by a dynamic array: work at the end is cheap, while anything near index 0 shifts every later element. Its methods split into in-place mutators that return `None` and operations like slicing, `sorted`, and `copy` that produce something new. Track object identity alongside contents, because the same list can answer to several names, and that is where most list surprises start.
Interview angles
What is the main purpose of **Creation**?+
Creation in Lists means constructing a new object with valid initial state. Compare literal syntax, constructors, and factory-style APIs where they exist, and note whether construction copies or reuses existing objects.
What should you pay attention to when using **Indexing and negative indexing**?+
An index selects one element. Positive indexes count from zero at the front, while negative indexes count backward from the end; an invalid element index raises IndexError.
How does **Slicing** fit into this lesson?+
A slice (items[start:stop:step]) selects a range by position and returns a new list, leaving the original untouched. Out-of-range bounds are clamped rather than reported, so items[10:] simply returns an empty list when the list is shorter.
What does `items = items.append("c")` leave in `items`?+
It leaves None: append mutates the list in place and returns None, so the assignment rebinds the name to that None and the original list is no longer reachable through items.