Sub topic 3
Slicing lists
This chapter assumes you can run Python code, index a list with items[0] and items[-1], and write a basic for loop. Slicing builds on indexing. A slice picks out a range of items instead of one, and it can also replace or delete a range.
The slice syntax
A slice has up to three parts separated by colons: items[start:stop:step]. Each part is optional.
startis the index of the first item to take. It is included.stopis the index where the slice ends. It is excluded.stepis the distance between taken items. It defaults to 1.
letters = ["a", "b", "c", "d", "e", "f"]
print(letters[1:4]) # ['b', 'c', 'd']
print(letters[:3]) # ['a', 'b', 'c']
print(letters[3:]) # ['d', 'e', 'f']
print(letters[-2:]) # ['e', 'f']
print(letters[:-1]) # ['a', 'b', 'c', 'd', 'e']
print(letters[::2]) # ['a', 'c', 'e']
print(letters[::-1]) # ['f', 'e', 'd', 'c', 'b', 'a']
print(letters[4:1:-1]) # ['e', 'd', 'c']Because stop is excluded, letters[1:4] has 4 - 1 = 3 items. Two adjacent slices, letters[:3] and letters[3:], split the list at index 3 with no overlap and no gap. This is why the half-open convention is used.
How Python evaluates a slice
Python fills in the missing parts, clamps the values to the list, and then walks from start toward stop by step.
The sign of the step controls the defaults. With a positive step, the defaults run from the front to the end. With a negative step they run from the end to the front, which is why letters[::-1] reverses the list.
You can see the resolved values with slice.indices, which takes the length of the sequence:
print(slice(None, None, -1).indices(6)) # (5, -1, -1)
print(slice(1, 100).indices(6)) # (1, 6, 1)The first result means "start at index 5, stop before index -1 (past the front), step -1". The second shows 100 clamped to the length, 6.
Slices never raise for out-of-range bounds
Indexing a missing position raises IndexError. Slicing does not. Out-of-range bounds are clamped, and an empty selection gives an empty list.
letters = ["a", "b", "c", "d", "e", "f"]
print(letters[10:]) # []
print(letters[2:100]) # ['c', 'd', 'e', 'f']
print(letters[4:2]) # []
print(letters[1:4:-1]) # []
try:
letters[10]
except IndexError as error:
print(error) # list index out of rangeThis is convenient, for example items[:5] is safe on a list of any length. It can also hide bugs. If a computed index is wrong, you may get an empty list instead of an error.
Two other errors are worth knowing. A step of zero raises ValueError: slice step cannot be zero. A float bound such as letters[1.0:3] raises TypeError, because slice bounds must be integers (or None).
A slice is a new list
A slice always creates a new list object. Changing the result does not change the original.
original = [10, 20, 30, 40]
part = original[1:3]
part[0] = 99
print(part) # [99, 30]
print(original) # [10, 20, 30, 40]The common idiom items[:] copies the whole list. It is a shallow copy, so the new list holds the same item objects as the old one. If those items are themselves lists, they are shared:
rows = [[1], [2]]
part = rows[:1]
part[0].append(9)
print(rows) # [[1, 9], [2]]
print(part) # [[1, 9]]The outer list is new, but part[0] and rows[0] are the same inner list. Aliasing and deep copies are covered in a later chapter.
Common slice forms
| Expression | Meaning |
|---|---|
| `a[:n]` | The first `n` items |
| `a[-n:]` | The last `n` items (see the warning below for `n = 0`) |
| `a[n:]` | Everything except the first `n` items |
| `a[:-n]` | Everything except the last `n` items (empty if `n = 0`) |
| `a[::2]` | Every second item, starting at index 0 |
| `a[1::2]` | Every second item, starting at index 1 |
| `a[::-1]` | A reversed copy |
| `a[:]` | A shallow copy |
Slice assignment
Because lists are mutable, a slice can appear on the left side of =. Python replaces that range of the original list with the items from the right side. The right side can be any iterable, and its length does not have to match.
nums = [0, 1, 2, 3, 4, 5]
nums[1:3] = [10, 20, 30] # replace 2 items with 3
print(nums) # [0, 10, 20, 30, 3, 4, 5]
nums[1:4] = [] # delete a range
print(nums) # [0, 3, 4, 5]
nums[1:1] = [7, 8] # insert without removing anything
print(nums) # [0, 7, 8, 3, 4, 5]An empty slice such as nums[1:1] selects no items, so assigning to it inserts at that position. This makes slice assignment a general tool that can insert, delete, and replace in one operation.
The right side is consumed as an iterable, so a string is split into characters:
letters = ["x", "y"]
letters[0:1] = "ab"
print(letters) # ['a', 'b', 'y']Assigning a single non-iterable value, as in letters[0:1] = 5, raises TypeError. Write letters[0:1] = [5] instead.
Extended slices need matching lengths
When the slice has a step other than 1, the replacement must have exactly as many items as the slice selects.
nums = [0, 7, 8, 3, 4, 5]
nums[::2] = ["a", "b", "c"] # selects indices 0, 2, 4
print(nums) # ['a', 7, 'b', 3, 'c', 5]
try:
nums[::2] = ["x", "y"]
except ValueError as error:
print(error) # attempt to assign sequence of size 2 to extended slice of size 3A slice with step 1 (including the default) can change the list's length. An extended slice cannot.
Deleting with slices
del accepts slices, including extended ones.
nums = ["a", 7, "b", 3, "c", 5]
del nums[::2]
print(nums) # [7, 3, 5]
del nums[:1]
print(nums) # [3, 5]del items[:] empties the list in place, which has the same effect as items.clear().
Replacing contents in place
Assigning to items[:] changes the existing list object instead of rebinding the name. This matters when other names, or a caller, refer to the same list.
def reset(items):
items[:] = [1, 2, 3] # mutates the caller's list
def rebind(items):
items = [1, 2, 3] # only changes the local name
data = ["old"]
rebind(data)
print(data) # ['old']
reset(data)
print(data) # [1, 2, 3]Reusable slice objects
The slice built-in creates a slice you can name and reuse. This is useful when the same range applies to several lists, such as columns in fixed positions.
first_three = slice(0, 3)
names = ["Ada", "Grace", "Alan", "Edsger"]
scores = [90, 85, 77, 95]
print(names[first_three]) # ['Ada', 'Grace', 'Alan']
print(scores[first_three]) # [90, 85, 77]Common mistakes
- Treating
stopas included.a[1:3]has two items, not three. Countstop - start. - Expecting an error on a bad range. Slices clamp silently. Check the result's length if the range matters.
- Mixing up negative steps and defaults. With a negative step,
startshould be the larger index.a[1:4:-1]is empty, whilea[4:1:-1]is not. - Assuming a slice is a deep copy.
a[:]copies only the outer list. - Assigning mismatched lengths to an extended slice. This raises
ValueError. - Using slices on huge lists in a loop. Each slice copies its items, so
items[1:]repeated in a loop does quadratic work. Use an index orcollections.dequefor that pattern.
Exercise
Given data = [5, 6, 7, 8, 9, 10], write one slice-assignment statement that changes data to [5, 0, 0, 0, 10]. Then say what data[::-2] would return for the original list.
Show answer
Use data[1:5] = [0, 0, 0]. The slice data[1:5] selects [6, 7, 8, 9] (four items), and the assignment replaces them with three zeros, so the list gets shorter. For the original list, data[::-2] starts at the last item and steps back by 2, giving [10, 8, 6].
Exercise
What does this code print, and why does it not raise an error? nums = [1, 2, 3, 4] nums[::2] = [9, 9] print(nums) print(nums[7:9])
Show answer
It prints [9, 2, 9, 4] and then []. The extended slice nums[::2] selects indices 0 and 2, which is two items, so the two-item replacement matches. The slice nums[7:9] is beyond the end of the list, and slices clamp out-of-range bounds instead of raising IndexError, so the result is an empty list.