Lists
List methods and mutability
Goal: Add, remove and sort items and know which operations change the original · 11 min
Lists are mutable: you can change them after creating them. The most important methods:
| method | effect | returns |
|---|---|---|
append(x) | add x at the end | None |
insert(i, x) | insert x before index i | None |
extend(other) | add all items of another list | None |
remove(x) | delete the first x (ValueError if absent) | None |
pop() / pop(i) | remove and return the last / i-th item | the item |
sort() | sort in place (reverse=True for descending) | None |
reverse() | reverse in place | None |
index(x) / count(x) | position of the first x / number of x | int |
Important: methods that change the list in place return None. A common bug is numbers = numbers.sort(), which replaces the list with None. Use numbers.sort() alone, or sorted(numbers), which returns a new sorted list and leaves the original untouched.
a = [3, 1, 2]
b = sorted(a) # b = [1, 2, 3], a unchanged
a.sort() # a = [1, 2, 3]
Assignment does not copy a list. b = a makes both names point to the same list, so changing one changes the other. Make a real (shallow) copy with a.copy(), list(a) or a[:].
Worked example: A shopping list
- Start with items = ["milk", "eggs"].
- append("bread") adds at the end; insert(0, "tea") adds at the front.
- pop() removes and returns "bread"; remove("eggs") deletes by value.
items = ["milk", "eggs"]
items.append("bread")
items.insert(0, "tea")
print(items)
print(items.pop())
items.remove("eggs")
print(items)Output:
['tea', 'milk', 'eggs', 'bread']
bread
['tea', 'milk']