Shallow copy traps, list multiplication gotchas, slicing edge cases, and the difference between sort() and sorted(). Lists hide many surprises.
a = [1, 2, 3] b = a.copy() # shallow copy b.append(4) print(a) print(b)
.copy() creates a new list, so a and b are separate objects. Appending to b doesn't affect a. Same result with b = a[:] or b = list(a).import copy a = [[1, 2], [3, 4]] b = a.copy() # shallow copy of outer list b[0].append(99) # mutate inner list print(a) print(b)
b[0] and a[0] point to the same inner list [1, 2]. Mutating it affects both. To avoid this, use copy.deepcopy(a) which recursively copies all nested objects.grid = [[0] * 3] * 3 # 3x3 grid of zeros grid[0][0] = 1 print(grid)
[[0]*3]*3 creates three references to the same inner list. Modifying grid[0][0] modifies the shared inner list — all three rows change. To create a true 2D grid, use: [[0]*3 for _ in range(3)] — this creates 3 independent inner lists.a = [0, 1, 2, 3, 4] print(a[1:3]) print(a[-2:]) print(a[::2]) print(a[::-1]) print(a[1:10]) # beyond end
[start:stop] — stop is exclusive. [-2:] — last 2 elements. [::2] — every 2nd element. [::-1] — reverse. [1:10] on a 5-element list — no error, just clips to the end. Slicing never throws IndexError.a = [0, 1, 2, 3, 4] a[1:3] = [10, 20, 30] print(a)
a[1:3] (elements 1 and 2 — two items) is replaced with [10, 20, 30] (three items). The list grows to accommodate. This is a powerful but surprising feature.a = [1, 2, 3] b = a[:] # full slice = copy print(a == b) print(a is b)
a[:] creates a new list with the same elements. == compares element-by-element → True. But is checks object identity — they are different list objects → False. a[:] is one of the most common idioms for copying a list.a = [3, 1, 4, 2] b = sorted(a) print(a) print(b) a.sort() print(a)
sorted(a) returns a new sorted list — a is unchanged. a.sort() sorts in place — a is modified — and returns None. A common bug: a = a.sort() sets a to None because .sort() returns None.a = [3, 1, 2] result = a.sort() print(result) print(a)
.sort() sorts in place and returns None. This is a classic trap: people write a = a.sort() expecting the sorted list, but a becomes None. Use sorted(a) when you need the result as a value.a = [1, 2, 2, 3, 2] a.remove(2) print(a) print(a.count(2))
.remove(x) removes only the first occurrence of x. It does not remove all occurrences. After removing the first 2, the list still has two 2s. If the value doesn't exist, .remove() raises ValueError.a = [1, 2, 3] print(a.pop()) print(a.pop(0)) print(a)
.pop() with no argument removes and returns the last element. .pop(0) removes and returns the element at index 0. After both pops, only [2] remains. Note: .pop(0) is O(n) — it shifts all elements. Use collections.deque for efficient front pops.a = [0] * 3 a[0] = 5 print(a)
[0]*3 creates 3 references to the same integer 0, but since integers are immutable, a[0] = 5 simply replaces the reference at index 0. The other elements still reference 0. This is safe for immutable types. The danger appears with mutable types like lists (see Q03).a = [1, 2] * 3 print(a) print(len(a))
[1, 2] * 3 concatenates the list 3 times. The resulting list has 6 elements. Since the elements are integers (immutable), this is safe — no shared reference problems.a = [10, 20, 30, 40] print(a[-1]) print(a[-2]) print(a[-4]) print(a[100] if 100 < len(a) else "out")
-1 is last, -2 is second-to-last, -4 is first (for a 4-element list). Accessing index 100 directly would raise IndexError — the ternary guard prevents that.a = [1, 2, 3] print(a[5])
IndexError when out of bounds. But slicing (a[1:100]) does NOT raise an error — it just clips. This asymmetry is important to know.a = [1, 2] b = [1, 2] a.append([3, 4]) b.extend([3, 4]) print(a) print(b)
.append(x) adds x as a single element — so a list becomes a nested element. .extend(iterable) adds each element of the iterable individually — no nesting. A very common confusion.a = [1, 2, 3] b = [4, 5] c = a + b d = a d += b print(a is d) print(c is a)
c = a + b creates a new list — so c is a is False. d = a makes d an alias for a. Then d += b calls d.__iadd__(b) — in-place extension — so d (and a) get the new items. a is d remains True.a = [3, 1, 2] b = ["banana", "apple", "cherry"] print(sorted(a, reverse=True)) print(sorted(b, key=len))
sorted(a, reverse=True) sorts in descending order. sorted(b, key=len) sorts strings by their length: "apple" (5), "banana" (6), "cherry" (6). When lengths tie, Python preserves original order (stable sort) — so "banana" comes before "cherry".a = [1, 2, 3] print(a * 0) print([] + []) print(len([None] * 5))
[None]*5 creates a list of 5 None values — very useful for pre-allocating fixed-size lists.