Lesson · Core Collections
Slicing Semantics
66 min readSlicing Semantics
Slicing is a compact language for selecting regular subsequences. Understanding start, stop, step, negative indexes, and copy behavior prevents many off-by-one errors.
Learning goals
- Normalize any slice (
values[1:5],values[1:5:2],values[::-1],values[-4:-1]) to the exact indexes it selects, and predict the result before running. - Explain how omitted start, stop, and step values adapt to the direction of the step.
- Read
slice(1, 5, 2)and itsindices(len(values))output as the normalized bounds a slice actually walks. - Distinguish slice behavior from element access: slices clamp out-of-range bounds, while a single index raises
IndexError. - Apply slice assignment correctly, including the length-matching requirement for extended (stepped) slices.
Mental model
The fixed order explains the surprising cases: bounds are resolved before any element is picked, which is why values[-4:-1] works exactly like its positive form and why values[10:20] returns [] instead of raising. A negative step flips both the walking direction and the defaults for omitted ends, so values[::-1] travels from the last element to the first.
A slice is a small program in a fixed order
normalize first, then walk
Mental model
the same mechanism as a compact list
sequence[start : stop : step] ↓ fill omitted parts: start and stop from the step's direction, step defaults to 1 ↓ normalize negatives against len(sequence) and clamp anything out of range ↓ walk from the effective start by step, stopping before the effective stop ↓ select those indexes into a NEW sequence
Core idea
A slice is a small program run in a fixed order: complete the omitted parts, normalize every bound against the sequence length, then walk from the effective start by the step and stop before the effective stop. Because normalization clamps instead of raising, slices degrade gracefully to shorter or empty results where a single index would raise IndexError. Because the walk builds a new sequence, built-in slices copy references rather than viewing the original, which matters as soon as the elements are themselves mutable.
sequence[start:stop:step]
Slice syntax selects indexes beginning at start, stopping before stop, and advancing by step. Each component can be omitted, and the rules also support negative indexes and steps.
Omitted boundaries
Omitted slice bounds default to the appropriate end of the sequence based on the step direction. With a negative step, the defaults reverse compared with normal forward slicing.
Negative indexes
Negative indexes are translated relative to sequence length: -1 refers to the last element. Slice normalization handles many out-of-range negative bounds without raising an error.
Negative steps
A negative slice step walks toward smaller indexes. Start/stop interpretation follows that direction, so reverse slices are easier to reason about after normalizing the bounds.
Reverse slicing
sequence[::-1] constructs a reversed slice for built-in sequences. It is concise, but reversed(sequence) can avoid materializing a full reversed copy when an iterator is enough.
Slice copies for built-in sequences
List, tuple, string, and bytes slicing normally creates a new outer sequence object containing the selected elements or data. For lists, referenced nested objects are not deep-copied.
Slice assignment for mutable sequences
List slice assignment replaces a selected range with items from an iterable and can change list length. Extended slices with a non-unit step generally require replacement lengths to match.
slice objects
slice(start, stop, step) stores slicing parameters as an object. Python passes slice objects to __getitem__, which lets custom containers implement normal slicing syntax.
Connecting slicing to __getitem__
When code uses obj[a:b:c], Python passes a slice(a, b, c) object to obj.__getitem__. A custom container can inspect the key and support integers, slices, or both.
Walkthrough
values = list("ABCDEF")builds['A', 'B', 'C', 'D', 'E', 'F'];values[1:5]takes indexes 1 through 4 and returns['B', 'C', 'D', 'E'], because index 5 is where the walk stops, not an element that is included.values[1:5:2]keeps the same start and stop and walks in twos, so it selects indexes 1 and 3, producing['B', 'D'].values[::-1]omits every part, and the negative step flips the defaults: the walk starts at the last element and moves down to the first, producing the full reversed list['F', 'E', 'D', 'C', 'B', 'A'].values[-4:-1]shows normalization in action: -4 becomes index 2 and -1 becomes index 5, so the result is['C', 'D', 'E']. The named slices = slice(1, 5, 2)reproducesvalues[1:5:2]throughvalues[s], ands.indices(len(values))prints(1, 5, 2), the exact trio the walk used. Predict before running: the four printed lists, and the two final lines.
Experiments to try
- Print
values[5:1:-1]and predict it first: it walks down from index 5 to index 2, producing['F', 'E', 'D', 'C']. Compare withvalues[::-1]and name the one element the shorter slice leaves out. - Try
values[10:20],values[-100:], andvalues[99]; record which calls return values and which raise, then state the rule that separates them. - Assign
s = slice(1, 5, 2)and reuseson a list and on a string; confirm the same parameters produce['B', 'D']and"BD", which shows a slice object is portable across sequence types. - Mutate through slice assignment:
letters = list("ABCDEF"), thenletters[1:3] = ["x"]and compare with a stepped version such asletters[::2] = ["1"], which raises because the replacement length must match a stepped slice.
Playable lesson
Lab: Slicing explorer
Provide start, stop, and step controls. Highlight normalized bounds and the exact elements selected, including negative indexes and reverse slices.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Slicing explorer
pick a slice or drag the controlsslice(None, None, None).indices(6) → (0, 6, 1)
values[start:stop:step] → ['A', 'B', 'C', 'D', 'E', 'F']
Common mistakes
- Treating the stop index as inclusive:
values[1:5]returns four elements because index 5 is the stopping point, and code that adds 1 to a stop "to include it" silently skips an element or overruns by one. - Forgetting that a negative step reverses the meaning of omitted bounds:
values[::-1]starts at the last element and walks down, while writingvalues[0::-1]starts at the first element and returns almost nothing. - Assuming every slice is a zero-copy view: built-in sequences build a new outer object filled with references to the selected elements, so mutating a nested list still shows through both sequences.
- Expecting out-of-range slices to raise: bounds are clamped during normalization, so
values[10:20]returns[]while the single-indexvalues[99]raisesIndexError.
Practice: Easy
- For
values = list("ABCDEF"), write the exact index set selected byvalues[1:5],values[1:5:2],values[-4:-1], andvalues[::-1]before running any of them, then check each printed list against your prediction. - Run
values[1:5]andvalues[1:6]side by side; name the extra element the second version adds and explain why the stop value itself is not an element. - Predict which of
values[10:20],values[-100:], andvalues[99]raise, then run all three and state the rule about clamping versus single-index access.
Practice: Medium
- Build
s = slice(1, 5, 2), printvalues[s], then prints.indices(len(values))and check each number in the tuple against the slice's start, stop, and step. - Create
steps = slice(None, None, -1)and comparevalues[steps]withvalues[::-1]; then callsteps.indices(len(values))and read how the negative step flips the normalized start and stop. - Slice a string, a tuple, and a list of the same six characters with
[1:5:2]. Note that each returns a same-shaped result of its own type, and say what that implies about slice copies.
Practice: Hard
- Implement a small class
Windowwrapping a list, with__getitem__that accepts an integer and, when given aslice, useskey.indices(len(self._items))to walk the underlying list. Test it withwindow[2],window[1:5:2], andwindow[::-1]. - Build a failure lab with three entries: a stop-boundary mistake that includes one element too many or too few, an out-of-range slice that returns
[]where single-index access raisesIndexError, and a stepped slice assignment such asletters[::2] = ["1"]that raisesValueErrorfor a length mismatch. Record each result and cite the rule behind it. - Reverse
valueswithvalues[::-1]and withreversed(values); show both produce the same items, then describe when the iterator is preferable (a single pass, no reversed copy in memory) and when the list is worth materializing.
Lesson checklist
- I can normalize any slice by hand: fill the defaults, resolve negatives, clamp the bounds, then walk.
- I can predict the four printed lists from the worked example without running it.
- I can explain why slices clamp where single-index access raises.
- I can use a
sliceobject and itsindices()output to describe a slice programmatically.
Remember
A slice runs in a fixed order: complete the omitted parts, normalize every bound against the sequence length, then walk from the effective start by the step and stop before the effective stop. Normalization is forgiving, so out-of-range slices return shorter or empty results while `values[99]` raises `IndexError`, and a negative step flips both the walk and the default ends. Built-in slicing copies references into a new sequence, which keeps `values[::-1]` simple at the cost of materializing the result.
Interview angles
What is the main purpose of **sequence[start:stop:step]**?+
Slice syntax selects indexes beginning at start, stopping before stop, and advancing by step. Each component can be omitted, and the rules also support negative indexes and steps.
What should you pay attention to when using **Omitted boundaries**?+
Omitted slice bounds default to the appropriate end of the sequence based on the step direction. With a negative step, the defaults reverse compared with normal forward slicing.
How does **Negative indexes** fit into this lesson?+
Negative indexes are translated relative to sequence length: -1 refers to the last element. Slice normalization handles many out-of-range negative bounds without raising an error.
Why does `values[10:20]` return an empty list while `values[99]` raises an error?+
Slice bounds are normalized and clamped against the sequence length, so an out-of-range slice degrades to the elements it can select, here none. A single index is not clamped, so it raises IndexError because no element sits at that position.