reference
5 min read
·
lesson 9 of 16 in Reference
Python Slicing Cheat Sheet
1 · The lesson
readQuick reference for sequence slicing. Works on list, tuple, str, bytes, range, and numpy arrays. For an intro see Lists.
1. Syntax
python
seq[start : stop : step]
setup added so this can run · defines seq, start, stop, step
# Lightweight mock for objects whose attributes/methods aren't critical class _AutoMock: def __init__(self, name='mock'): self._name = name def __getattr__(self, k): return _AutoMock(self._name + '.' + k) def __call__(self, *a, **kw): print('-> ' + self._name + '() called') return _AutoMock(self._name + '()') def __repr__(self): return '<mock ' + self._name + '>' def __str__(self): return '<mock ' + self._name + '>' def __bool__(self): return True def __iter__(self): return iter([]) def __len__(self): return 0 def __getitem__(self, k): return _AutoMock(self._name + '[...]') def __setitem__(self, k, v): pass def __enter__(self): return self def __exit__(self, *a): return False async def __aenter__(self): return self async def __aexit__(self, *a): return False def __add__(self, o): return self def __radd__(self, o): return self def __sub__(self, o): return self def __mul__(self, o): return self def __rmul__(self, o): return self def __truediv__(self, o): return self def __eq__(self, o): return isinstance(o, _AutoMock) def __hash__(self): return hash(self._name) def __lt__(self, o): return True def __le__(self, o): return True def __gt__(self, o): return False def __ge__(self, o): return False def __mro_entries__(self, bases): return (object,) seq = ["alpha", "beta", "gamma"] start = _AutoMock('start') stop = _AutoMock('stop') step = _AutoMock('step')
All three are optional. stop is exclusive.
| Omitted | Defaults to |
|---|---|
start | 0 (or len-1 if step<0) |
stop | len(seq) (or -len-1) |
step | 1 |
python
xs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(xs[2:5]) # [2, 3, 4] print(xs[:3]) # [0, 1, 2] print(xs[7:]) # [7, 8, 9] print(xs[:]) # full copy
2. Negative Indices
-1 is the last element, -2 second-last, and so on.
python
xs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(xs[-1]) # 9 print(xs[-3:]) # [7, 8, 9] last 3 print(xs[:-2]) # [0..7] all but last 2 print(xs[-5:-2]) # [5, 6, 7]
3. Step & Reverse
python
xs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(xs[::2]) # [0, 2, 4, 6, 8] every other print(xs[1::2]) # [1, 3, 5, 7, 9] odd indices print(xs[::-1]) # [9..0] reverse print(xs[::-2]) # [9, 7, 5, 3, 1] reverse every other print(xs[5::-1]) # [5, 4, 3, 2, 1, 0] half-reverse from index 5
4. Slice Assignment (Lists Only)
Slices on mutable sequences can be assigned to and replace the chunk:
python
xs = [1, 2, 3, 4, 5] xs[1:3] = [9, 9, 9] # [1, 9, 9, 9, 4, 5] length can change xs[::2] = [0, 0, 0, 0] # extended slice needs same length del xs[1:3] # removes those indices
5. The slice() Object
Useful when you want to store or pass a slice:
python
arr = list(range(20)) s = slice(2, 15, 3) arr[s] # [2, 5, 8, 11, 14] arr[s] == arr[2:15:3] # True
6. What Slicing Works On
| Type | Read | Write | Notes |
|---|---|---|---|
list | yes | yes | Slice = shallow copy |
tuple | yes | no | Returns new tuple |
str | yes | no | Strings are immutable |
bytes | yes | no | Use bytearray for mutable |
bytearray | yes | yes | Like a list of ints |
range | yes | no | Returns new range |
| numpy array | yes | yes | Slices are views, not copies |
dict | no | no | Use dict.items() / comprehensions / itertools |
set | no | no | Unordered |
| generator | no | no | Use itertools.islice — see itertools cheat |
7. Out-of-range Behaviour
Indexing one past the end raises; slicing silently clips:
python
xs = [1, 2, 3] xs[10] # IndexError xs[10:20] # [] OK, empty slice xs[1:99] # [2, 3] clipped
Common Patterns
python
# Last N items last3 = xs[-3:] # First N items first3 = xs[:3] # All but last trunc = xs[:-1] # All but first tail = xs[1:] # Reverse rev = xs[::-1] rev_s = s[::-1] # Every Nth every2 = xs[::2] # Shallow copy copy = xs[:] # Replace middle of list in place xs[2:5] = [99, 99] # Chunk strings (fixed width) chunks = [s[i:i+4] for i in range(0, len(s), 4)] # Trim known prefix / suffix core = s[4:-4] # safer than two .replace calls # Rotate list rot = xs[k:] + xs[:k]
setup added so this can run · defines xs, s, k
# Lightweight mock for objects whose attributes/methods aren't critical class _AutoMock: def __init__(self, name='mock'): self._name = name def __getattr__(self, k): return _AutoMock(self._name + '.' + k) def __call__(self, *a, **kw): print('-> ' + self._name + '() called') return _AutoMock(self._name + '()') def __repr__(self): return '<mock ' + self._name + '>' def __str__(self): return '<mock ' + self._name + '>' def __bool__(self): return True def __iter__(self): return iter([]) def __len__(self): return 0 def __getitem__(self, k): return _AutoMock(self._name + '[...]') def __setitem__(self, k, v): pass def __enter__(self): return self def __exit__(self, *a): return False async def __aenter__(self): return self async def __aexit__(self, *a): return False def __add__(self, o): return self def __radd__(self, o): return self def __sub__(self, o): return self def __mul__(self, o): return self def __rmul__(self, o): return self def __truediv__(self, o): return self def __eq__(self, o): return isinstance(o, _AutoMock) def __hash__(self): return hash(self._name) def __lt__(self, o): return True def __le__(self, o): return True def __gt__(self, o): return False def __ge__(self, o): return False def __mro_entries__(self, bases): return (object,) xs = ["alpha", "beta", "gamma"] s = ["alpha", "beta", "gamma"] k = _AutoMock('k')
Common Errors
| Error / Symptom | Cause | Fix |
|---|---|---|
TypeError: 'str' object does not support item assignment | Tried s[0] = "x" or s[1:3] = "ab" | Rebuild: s = s[:1] + "x" + s[2:] or use a list |
TypeError: unhashable type: 'slice' | Used a slice in a dict / set | Convert to tuple(arr[s]) |
ValueError: attempt to assign sequence of size N to extended slice of size M | Extended-step slice assign with wrong length | Match the lengths exactly |
Got [] from xs[5:2] | start >= stop with positive step | Set step=-1 for reverse-order slicing |
TypeError: 'dict_keys' object is not subscriptable | Sliced d.keys() directly | list(d.keys())[:3] |
| numpy mutation surprises original | Slices are views | arr[1:4].copy() when you need an independent copy |
See Also
- Lists and Lists cheat
- Strings and Strings cheat
- Itertools cheat for slicing iterators
Practice this
on practicepython.inShort exercises that run in your browser and tell you what your code actually did, not just whether a test passed.