10.7 List Methods
A consolidated reference for every built-in list method, grouped by what it does -- add (append, extend, insert), remove (remove, pop, clear), query (index, count), and reorder/copy (sort, reverse, copy).
All eleven list methods, grouped by what they do. append/extend/insert and remove/pop/clear were already covered individually in 10.4 Modifying Lists and 10.5 Removing Elements — this is the complete lookup table.
| Method | Example | Result |
|---|---|---|
append(x) |
[1,2].append(3) |
[1, 2, 3] |
extend(it) |
[1,2].extend([3,4]) |
[1, 2, 3, 4] |
insert(i, x) |
[1,2].insert(0, 0) |
[0, 1, 2] |
remove(x) |
[1,2,3,2].remove(2) |
[1, 3, 2] |
pop([i]) |
[1,2,3].pop() |
returns 3 |
clear() |
[1,2].clear() |
[] |
index(x) |
[1,2,3,2].index(2) |
1 |
count(x) |
[1,2,3,2].count(2) |
2 |
sort() |
[3,1,2].sort() |
in place → [1, 2, 3], returns None |
reverse() |
[1,2,3].reverse() |
in place → [3, 2, 1] |
copy() |
l.copy() |
shallow copy, equivalent to l[:] |
Query Methods
index() returns the position of the first matching value and raises ValueError if absent — the list equivalent of str.index() (see 9.7 Common String Methods). count() returns how many times a value appears.
>>> [1, 2, 3, 2].index(2)
1
>>> [1, 2, 3, 2].count(2)
2
sort()
Sorts the list in place and returns None — a common gotcha is writing l = l.sort(), which discards the list entirely. See 10.12 Sorting and Searching for sort() vs. sorted().
>>> l = [3, 1, 2]
>>> l.sort()
>>> l
[1, 2, 3]
reverse()
Reverses the list in place — distinct from the l[::-1] slice idiom, which returns a new list instead.
>>> l = [1, 2, 3]
>>> l.reverse()
>>> l
[3, 2, 1]
copy()
Returns a shallow copy — equivalent to l[:] (see 10.3 List Indexing and Slicing and 10.11 Copying and Mutability).
>>> l2 = l.copy()
>>> l2 is l
False
Quick Interview Answer
“The eleven list methods split cleanly into four groups: add (
append,extend,insert), remove (remove,pop,clear), query (index,count— read-only, no mutation), and reorder/copy (sort,reverse,copy). The one detail worth memorizing cold:sort()andreverse()both mutate in place and returnNone— assigning their result (l = l.sort()) silently throws the list away.”
Common Mistakes
- Writing
l = l.sort()expecting the sorted list back —sort()returnsNone; the list is already sorted in place, so just useldirectly afterward. - Using
index()when the value might not be present — it raisesValueErrorinstead of returning a sentinel like-1; checkinfirst or catch the exception. - Confusing
l.reverse()(in-place, mutates, returnsNone) withl[::-1]orreversed(l)(both return a new sequence, original untouched).
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form