Changing a list
🌍 In real life. A list of names on a whiteboard can change all day: you add a new name at the bottom, squeeze one in at the top, rub one out, or write over a misspelt one. It's still the same whiteboard.
Unlike a string, a Python list works like that whiteboard: you can change it in place.
The idea in one sentence: a list is mutable: append, insert and [i] = x put items in, and pop and remove take them out, all changing the same list.
Its words:
- mutable: can be changed after it's made (strings are not; lists are)
append(x): add at the end;insert(i, x): add at index ipop(): take off the last item and give it back;remove(x): delete the first xextend(other): add every item of another list
Step by step, for the shelf below:
numsstarts as[5, 8].append(3)adds 3 at the end:[5, 8, 3].insert(0, 9)puts 9 at the front, and the others move along:[9, 5, 8, 3].[1] = 7writes over index 1:[9, 7, 8, 3].
nums = [5, 8]
nums.append(3)
nums.insert(0, 9)
nums[1] = 7
print(nums)Two ways to take things out:
nums.pop()takes the last item off and gives it back, so you can keep it.nums.pop(i)takes the item at indexi.nums.remove(x)deletes the firstxit finds.
nums = [9, 7, 8, 3]
last = nums.pop()
print("took", last)
nums.remove(9)
print(nums)A very common pattern: start with an empty list [] and append to it inside a loop.
squares = []
for n in range(1, 4):
squares.append(n * n)
print(squares)Adding many at once: extend. nums.append([4, 5]) adds one item, a list inside the list. nums.extend([4, 5]) adds each item of the other list. nums + [4, 5] makes a new list and leaves nums as it was, while nums += [4, 5] changes nums like extend.
a = [1, 2]
a.append([3, 4])
print(a)
b = [1, 2]
b.extend([3, 4])
print(b)
c = [1, 2]
print(c + [3], c)Replacing a whole slice. Assigning to a slice swaps that stretch of the list for the items on the right, and the two don't need the same length: nums[1:3] = ["x"] replaces two items with one. An empty slice like nums[1:1] slips items in without removing any, and nums[1:3] = [] deletes that stretch. del nums[i] deletes one item by its index.
nums = [1, 2, 3, 4, 5]
nums[1:3] = ["x"]
print(nums)
nums[1:1] = [7, 8]
print(nums)
del nums[0]
print(nums)What it costs. Working at the end of a list is instant: append and pop() don't disturb the other items. Working at the front or middle is not: insert(0, x) has to move every item one slot to the right to make room, and pop(0) and remove(x) move everything after the gap one slot to the left. On a list of a million items that's up to a million moves each time. Chapter 40 shows a tool built for fast work at both ends.
Mistakes and edge cases.
- Keeping what append gives back.
nums = nums.append(3)makesnumsNone: list methods that change the list give backNone. Just writenums.append(3). - pop() on an empty list.
[].pop()givesIndexError: pop from empty list. - Removing something that isn't there.
[1, 2].remove(5)givesValueError: list.remove(x): x not in list. Check withinfirst. - append instead of extend.
a.append([3, 4])adds one item, a list inside the list. - Removing while looping over the same list. Items move left under the loop, so some are skipped:
[1, 2, 2, 3]loses only one 2. Build a new list instead.
Quiz
What does this print?
a = [1, 2] a.append(3) a.append(4) print(a)What does this print?
a = ["b", "c"] a.insert(0, "a") print(a)What does this print?
a = [10, 20, 30] x = a.pop() print(x, a)What does this print?
a = [3, 1, 3] a.remove(3) print(a)How do you change the first item of
numsto 0?- nums[0] = 0
- nums.append(0)
- nums = 0
Which line has a mistake?
names = ["Ana", "Bo"] names.remove("Cy") print(names)
Coding tasks
Start with
shopping = ["milk", "eggs"]. Add"bread"to the end, put"tea"at the front, then print the list.Ask for 3 whole numbers, one at a time. Put them in a list, in the order they were typed, and print the list.
Start with
names = ["Ana", "Bo", "Cy"]. Ask for a name. If it is in the list, remove it. If not, printnot found. Either way, print the list at the end.