Add, remove, reorder and search: the methods that change a list in place.
# add to end
fruits = ["apple", "banana"]
fruits.append("cherry")
# ans: ["apple", "banana", "cherry"]
# insert at index
fruits = ["apple", "cherry"]
fruits.insert(1, "banana")
# ans: ["apple", "banana", "cherry"]
Everything from index 1 onwards shifts one place right to make room.
# add multiple items
fruits = ["apple"]
fruits.extend(["banana", "cherry"])
# ans: ["apple", "banana", "cherry"]
# remove by value
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
# ans: ["apple", "cherry"]
# remove and return
fruits = ["apple", "banana", "cherry"]
last = fruits.pop()
# ans: last is "cherry"
# ans: fruits is ["apple", "banana"]
first = fruits.pop(0)
# ans: first is "apple"
Without an index, pop() takes the last item; pop(0) takes the first.
# sort in place
numbers = [3, 1, 4, 1, 5]
numbers.sort()
# ans: [1, 1, 3, 4, 5]
numbers.sort(reverse=True)
# ans: [5, 4, 3, 1, 1]
# reverse in place
lst = [1, 2, 3]
lst.reverse()
# ans: [3, 2, 1]
# count occurrences
numbers = [1, 2, 3, 2, 4, 2]
numbers.count(2)
# ans: 3
# find index
fruits = ["apple", "banana", "cherry"]
fruits.index("banana")
# ans: 1
index scans from the left and stops at the first match.
# remove all
fruits = ["apple", "banana"]
fruits.clear()
# ans: []
Predict the result, then press → to check.
# what is lst after append?
lst = [1, 2]
lst.append(3)
# ans: [1, 2, 3]
# insert at position?
lst = [1, 3, 4]
lst.insert(1, 2)
# ans: [1, 2, 3, 4]
# extend vs append?
lst = [1, 2]
lst.extend([3, 4])
# ans: [1, 2, 3, 4]
lst = [1, 2]
lst.append([3, 4])
# ans: [1, 2, [3, 4]]
extend adds each item; append adds the whole list as one item.
# pop without argument?
lst = [1, 2, 3]
lst.pop()
# ans: 3
# ans: lst is [1, 2]
# remove first occurrence?
lst = [1, 2, 2, 3]
lst.remove(2)
# ans: [1, 2, 3]
# sort return value?
lst = [3, 1, 2]
result = lst.sort()
# ans: result is None (sorts in place)
Use sorted(lst) when you want a new sorted list back.
# index not found?
lst = [1, 2, 3]
lst.index(5)
# ans: ValueError
# count non-existent?
lst = [1, 2, 3]
lst.count(5)
# ans: 0
# reverse return?
lst = [1, 2, 3]
result = lst.reverse()
# ans: result is None (reverses in place)
# clear return?
lst = [1, 2, 3]
result = lst.clear()
# ans: result is None
# ans: lst is []
| Method | Does | Returns |
|---|---|---|
| append(x) | adds x at the end | None |
| insert(i, x) | adds x before index i | None |
| extend(items) | adds each item | None |
| remove(x) | deletes the first x | None |
| pop(i=-1) | deletes item i | that item |
| sort() / reverse() | reorders in place | None |
| count(x) / index(x) | searches | a number |
| clear() | empties the list | None |