Read the half-open endpoints of a slice
Type one expression at a time and check its delimiters. · 184 words
A Python slice selects part of a sequence using a half-open interval: the start index is included, while the stop index is excluded. In list[start:stop], start means "begin here" and stop means "stop before here." For example, readings = [10, 20, 30, 40, 50] and readings[1:4] selects indices 1, 2, and 3, producing [20, 30, 40]. Index 4 is not included because it is the stop value. This rule makes adjacent slices fit together without repeating an item: readings[:3] is [10, 20, 30], and readings[3:] is [40, 50].
The same rule is useful when preparing experiment data. Suppose tokens = ["review", "was", "useful", "and", "fast"] and you want the first three tokens for a prompt but the remaining tokens for later analysis. tokens[:3] gives ["review", "was", "useful"], while tokens[3:] gives ["and", "fast"]. The boundary token "useful" appears in the first slice only, and "and" appears in the second only. A slice can also omit its endpoints: tokens[:] copies the whole list, and tokens[::2] takes every second item, starting at index 0. When an endpoint is absent, Python uses the appropriate end of the sequence.
Check your recall
For values = [10, 20, 30, 40, 50], what is values[1:4], and which indices does it include?
Check your answer
The result is [20, 30, 40]. It includes indices 1, 2, and 3. The stop index 4 is excluded.
Sources and credits
Original KeyTouch lesson. Background reading · Python Software Foundation · The Python Tutorial.