Python List Slicing
What you will learn
- How slicing a list works (it matches string slicing)
- That a slice is a new list
- Common cuts: first n, last n, all but the ends, reversing
- How to assign to a slice to replace, insert or delete pieces
- Rotating and chunking a list
You met slicing on strings (lesson 4.2). Lists use exactly the same rules, with one big addition: because lists are mutable, you can also assign to a slice.
1. Slicing a list
lst[start:stop:step] takes the items from start up to, but not including, stop:
n = [10, 20, 30, 40, 50, 60]
print(n[1:4])
print(n[:3])
print(n[3:])
print(n[-2:])
print(n[:-2])
print(n[::2])
print(n[::-1])
print(n[4:1:-1])
[20, 30, 40]
[10, 20, 30]
[40, 50, 60]
[50, 60]
[10, 20, 30, 40]
[10, 30, 50]
[60, 50, 40, 30, 20, 10]
[50, 40, 30]
| Slice | Meaning |
|---|---|
n[1:4] |
indexes 1, 2 and 3 |
n[:3] |
the first 3 items |
n[3:] |
everything from index 3 |
n[-2:] |
the last 2 items |
n[:-2] |
all but the last 2 |
n[::2] |
every second item |
n[::-1] |
the list reversed |
As with strings, a slice never raises an out-of-range error. It gives a shorter list, or an empty one:
print(n[10:], n[:100], n[4:2], n[-100:2])
[] [10, 20, 30, 40, 50, 60] [] [10, 20]
Quick check: what is `[1, 2, 3, 4][1:3]`?
[2, 3]. It includes index 1 and 2, and stops before 3.
2. A slice is a new list
A slice copies the chosen items into a new list. Changing the slice does not change the original:
n = [10, 20, 30, 40, 50, 60]
s = n[1:3]
s[0] = "X"
print(s, n)
['X', 30] [10, 20, 30, 40, 50, 60]
n[:] is therefore a quick copy of the whole list:
c = n[:]
c.append(70)
print(c == n, c is n, len(c), len(n))
False False 7 6
This is a shallow copy: the items are shared, which matters for lists inside lists (lesson 7.5).
3. Assigning to a slice
You can put a slice on the left of = and give it a list of new items. The slice is replaced, and the list grows or shrinks to fit:
items = ["x", "y", "z"]
items[1:2] = ["Y1", "Y2"]
print(items)
['x', 'Y1', 'Y2', 'z']
The slice [1:2] held one item ("y"), and was replaced by two. That makes assignment a general tool:
| Goal | Code |
|---|---|
| replace a piece | items[1:3] = ["A"] |
| insert at the start | items[0:0] = ["start"] |
| append at the end | items[len(items):] = ["end"] |
| delete a piece | items[1:3] = [] |
| replace everything | items[:] = [1, 2, 3] |
items = ["x", "y", "z"]
items[1:2] = ["Y1", "Y2"]
items[0:0] = ["start"]
items[len(items):] = ["end"]
print(items)
items[-1:] = []
print(items)
items[1:3] = []
print(items)
items[:] = [1, 2, 3]
print(items)
['start', 'x', 'Y1', 'Y2', 'z', 'end']
['start', 'x', 'Y1', 'Y2', 'z']
['start', 'Y2', 'z']
[1, 2, 3]
items[:] = ... changes the same list (other names that point to it see the change). That is different from items = [...], which makes a new list.
Slices with a step
A slice with a step (an extended slice) must be given exactly as many items as it holds:
nums = [1, 2, 3, 4, 5, 6]
nums[::2] = [0, 0, 0]
print(nums)
nums[::2] = [9, 9]
[0, 2, 0, 4, 0, 6]
ValueError: attempt to assign sequence of size 2 to extended slice of size 3
The three even positions were replaced by three zeros. Two values for three slots is an error.
4. Deleting slices
The del statement removes a slice, with or without a step (lesson 7.2):
d = [0, 1, 2, 3, 4, 5, 6]
del d[1:3]
print(d)
del d[::2]
print(d)
del d[:]
print(d)
[0, 3, 4, 5, 6]
[3, 5]
[]
5. Useful cuts
| Task | Code |
|---|---|
first n items |
lst[:n] |
last n items |
lst[-n:] (careful: n = 0 gives the whole list) |
| all but the first | lst[1:] |
| all but the last | lst[:-1] |
| all but the first and last | lst[1:-1] |
| the middle onwards | lst[len(lst) // 2:] |
| every second item | lst[::2] |
| reversed copy | lst[::-1] |
Rotating
Join two slices to move items from one end to the other:
r = [1, 2, 3, 4, 5]
print(r[1:] + r[:1])
print(r[-1:] + r[:-1])
[2, 3, 4, 5, 1]
[5, 1, 2, 3, 4]
The first moves the first item to the end, and the second moves the last item to the front.
Chunking
Cut a long list into pieces of a fixed size by stepping the start with range:
data = list(range(1, 11))
print([data[i:i + 3] for i in range(0, len(data), 3)])
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
The last piece is shorter, because a slice stops at the end of the list.
6. Slice objects
A slice can be stored in a name and used again, with slice(start, stop, step):
sl = slice(1, 5, 2)
print(data[sl], sl.start, sl.stop, sl.step)
[2, 4] 1 5 2
A slice object can be used on any sequence, and on the left of = as well.
7. Errors
The start and stop must be whole numbers (or left out):
words = ["a", "b", "c"]
words[1.5:3]
TypeError: slice indices must be integers or None or have an __index__ method
And a list takes only indexes or slices, not text: words["1:2"] raises TypeError: list indices must be integers or slices, not str.
Tuples and strings slice the same way, but they give a tuple or a string back, and you cannot assign to their slices.
Worked example: pages of results
Show a list of ten results three at a time. Work out the slice for any page number.
results = list(range(1, 11))
size = 3
for page in (1, 2, 4):
start = (page - 1) * size
print(page, results[start:start + size])
1 [1, 2, 3]
2 [4, 5, 6]
4 [10]
| Page | start |
Slice | Items |
|---|---|---|---|
| 1 | 0 | [0:3] |
1, 2, 3 |
| 2 | 3 | [3:6] |
4, 5, 6 |
| 4 | 9 | [9:12] |
10 only |
Page 4 has just one item, because the slice stops at the end. A page past the end, such as page 5, would give an empty list, with no error. The results are numbers made up for the example.
Common mistakes
- Expecting the stop index to be included.
- Thinking
lst[:]or a slice shares the original. It is a new list, but a shallow one. - Using
lst[-n:]withn = 0. It returns the whole list, not an empty one. - Assigning the wrong number of items to a stepped slice.
- Using a float or text as a slice bound.
- Writing
lst = lst[:]and expecting an in-place change. It rebinds the name to a new list.
Key takeaways
lst[start:stop:step]gives a new list; stop is excluded; slices never go out of range.lst[:n]is the firstn,lst[-n:]the lastn,lst[::-1]the reverse,lst[:]a shallow copy.- Assigning to a slice replaces, inserts or deletes pieces, and the list changes size as needed.
- A stepped slice needs exactly as many new items as it holds.
- Rotate with
lst[1:] + lst[:1]; chunk withlst[i:i + size]overrange(0, len(lst), size).
Practice
1. With n = [5, 6, 7, 8, 9], what are n[:2], n[-2:] and n[1:-1]?
Show answer
[5, 6], [8, 9] and [6, 7, 8].
2. Write one line that replaces the items at index 1 and 2 of lst with the single item "X".
Show answer
lst[1:3] = ["X"].
3. Insert "new" at the start of lst using a slice.
Show answer
lst[0:0] = ["new"].
4. What does [1, 2, 3, 4][::-1] give? Does it change the original?
Show answer
[4, 3, 2, 1]. The original is not changed, because a slice is a new list.
5. Cut list(range(1, 8)) into chunks of 3.
Show answer
data = list(range(1, 8))
chunks = [data[i:i + 3] for i in range(0, len(data), 3)]
chunks is [[1, 2, 3], [4, 5, 6], [7]].
6. Why does nums[::2] = [9, 9] fail for a list of 6 items?
Show answer
A stepped slice of 6 items holds 3 positions, and you must assign exactly 3 values. Two values raise ValueError: attempt to assign sequence of size 2 to extended slice of size 3.