Half-Open Slices of Sequences
A slice with step one usually includes its start offset and excludes its stop offset. Its bounds describe the spaces between successive elements.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Read a sample slice
In "paper", the Python slice [1:4] selects positions 1, 2, and 3 to yield "ape". For \(0\le a\le b\le n\), the length is \(b-a\). See zero-based indexing for why the stop can equal \(n\).
Join neighboring spans
The slices [:2] and [2:] yield "pa" and "per". Their concatenation recovers the original. The inclusive and exclusive boundary convention makes the offsets meet without overlap.[1]
Use a split point in both adjacent slices
With values [3, 5, 8, 13, 21] and split point two, values[:2] contains [3, 5] and values[2:] contains [8, 13, 21]. Concatenating them reconstructs the source for every split point from zero through its length. The half-open convention makes position two the first element of the right slice. Test splitting at both ends to verify that the other side contains everything. See zero-based indexing.
Check when slicing returns fewer values than requested
A parser expecting four fixed-width symbols starting at position three needs to check the returned length. On a source of length six, source[3:7] returns only three positions under Python's clipping rules. A successful slice operation therefore does not prove that the source contained a whole field. An empty result can be meaningful for an interval between equal boundaries. See reading a fixed-size block for the analogous case with a byte source.