Sub topic 3
Slicing lists
This chapter assumes you can already index a list with fruits[0] and fruits[-1], and that you know lists are mutable. Slicing extends indexing from one item to a range of items.
The slice model
A slice has the form items[start:stop:step]. It returns a new list. start is included and stop is excluded. Any of the three parts can be left out.
nums = [10, 20, 30, 40, 50, 60]
print(nums[1:4]) # [20, 30, 40]
print(nums[:2]) # [10, 20]
print(nums[4:]) # [50, 60]
print(nums[-2:]) # [50, 60]
print(nums[::2]) # [10, 30, 50]
print(nums[::-1]) # [60, 50, 40, 30, 20, 10]Think of the indices as pointing at the gaps between items, not at the items. The slice [1:4] takes everything between gap 1 and gap 4. Because stop is excluded, nums[:k] + nums[k:] always equals nums, and stop - start is the length of the result when step is 1.
| Form | Meaning |
|---|---|
| `a[i:j]` | Items from index `i` up to, but not including, `j` |
| `a[:j]` | The first `j` items |
| `a[i:]` | Everything from `i` to the end |
| `a[-n:]` | The last `n` items |
| `a[::k]` | Every `k`-th item |
| `a[::-1]` | A reversed copy |
Slices never raise IndexError
Indexing past the end raises IndexError. Slicing clamps out-of-range bounds instead.
nums = [10, 20, 30, 40, 50, 60]
print(nums[2:100]) # [30, 40, 50, 60]
print(nums[10:]) # []This is convenient, but it can hide off-by-one bugs, because a wrong bound gives a shorter list and no error.
Slices are shallow copies
A slice builds a new list, but it holds the same item objects as the original. For numbers and strings this does not matter. For nested lists, both lists share the inner lists.
rows = [[1, 2], [3, 4]]
part = rows[:] # same as rows.copy()
part.append([5, 6]) # only part changes
part[0].append(99) # the shared inner list changes
print(rows) # [[1, 2, 99], [3, 4]]
print(part) # [[1, 2, 99], [3, 4], [5, 6]]Chapter material on aliasing and deep copies covers this in more detail.
Slice assignment
A slice on the left side of = replaces that part of the list in place. The replacement can have a different length, so the list can grow or shrink.
letters = ["a", "b", "c", "d", "e"]
letters[1:3] = ["X", "Y", "Z"]
print(letters) # ['a', 'X', 'Y', 'Z', 'd', 'e']
letters[1:4] = []
print(letters) # ['a', 'd', 'e']
letters[1:1] = ["m", "n"]
print(letters) # ['a', 'm', 'n', 'd', 'e']
del letters[:2]
print(letters) # ['n', 'd', 'e']An empty slice such as [1:1] inserts without removing anything. Assigning [] deletes. The right side can be any iterable, so letters[0:0] = "hi" inserts 'h' and 'i' as separate items.
When the slice has a step other than 1, the sizes must match exactly:
vals = [0, 1, 2, 3, 4, 5]
vals[::2] = [9, 9, 9]
print(vals) # [9, 1, 9, 3, 9, 5]
try:
vals[::2] = [1, 2]
except ValueError as err:
print(err) # attempt to assign sequence of size 2 to extended slice of size 3Common errors
- Expecting
stopto be included.nums[1:3]has two items, not three. - Calling
nums[::-1]and expectingnumsto change. The slice returns a reversed copy. Usenums.reverse()to reverse in place. - Assuming
b = a[:]is a deep copy. It is shallow. - Using a step with mismatched sizes in slice assignment.
- Mixing up
nums[-3:-1]withnums[-3:]. The first excludes the last item.
Exercise
Given data = [5, 4, 3, 2, 1, 0], what do data[1:5:2] and data[-2:] return? Then write one statement that replaces the middle two items (indices 2 and 3) with the three items "x", "y" and "z".
Show answer
data[1:5:2] returns [4, 2], because it takes indices 1 and 3. data[-2:] returns [1, 0]. The statement is data[2:4] = ["x", "y", "z"], which leaves [5, 4, 'x', 'y', 'z', 1, 0].