Slice Bounds and Single-Index Bounds
Python's built-in sequences treat excessive slice endpoints and an excessive single index differently.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace an oversized request
On a sequence of length three, items[5] raises an index error. The slice items[5:9] returns an empty subsequence. Slice boundaries are clipped for built-in sequences, which can be useful for selecting a preview.
Check whether an empty result is valid
A request for the fifth report row may need a clear missing-row message. A preview asking for up to five rows can accept fewer. A function contract should say whether limits are requests, requirements, or exact indices.[1]
Choose the shape for an empty result
On ["ant", "bee"], index one returns the string "bee" and slice [1:2] returns a list containing that string. Index two raises, but slice [2:3] returns an empty list. If a parser requires one token, the scalar access or explicit validation should detect truncation. If an interface accepts any number of matching tokens, an empty sequence can be a useful outcome. See function postconditions for documenting shape and absence.
Check what a copy actually owns
A Python list slice is a new outer list. On rows = [[4], [9]], a slice selecting the first row still shares the inner list with rows. Mutating the inner list is visible through both names. Replacing the first slot of the slice leaves the corresponding slot in rows untouched. A test should exercise both mutations if the API promises independent results. See copying a sequence slice.