A slice object represents the start, stop, and step parameters used to select part of a sequence. The expression sequence[start:stop:step] is equivalent to sequence[slice(start, stop, step)]. section 4.1 section 4.1.2
Use slice objects when the selection needs a name or must be reused:
- Create one with slice(start, stop, step); omitted parameters can be represented with the corresponding shorter constructor form. section 4.1.2
- Apply it as a sequence subscript: numbers[slice(1, 10, 2)] produces [1, 3, 5, 7, 9]. section 4.1.2
- Prefer meaningful names such as task_title or task_urgency when parsing consistently formatted text; updating indices then requires changing the slice definition rather than every access. section 4.1.3
- Distinguish slices from ranges: ranges are iterable, whereas slices serve as sequence subscripts and are not iterable. section 4.1.2
Parse fixed-width task records
task_id = slice(5) task_title = slice(5, 20) task_desc = slice(20, 48) task_urgency = slice(48, 49) for line in task_lines: task = (line[task_id].strip(), line[task_title].strip(), line[task_desc].strip(), line[task_urgency].strip()) # ('1001', 'Laundry', 'Wash all clothes', '3') section 4.1.3
Slice objects also support list “surgery”: assign to a selected slice to replace, extend, or shrink a mutable sequence, or delete it with del. Strided assignments update selected positions, while negative steps process from right to left and require caution. section 4.1.4 section 4.1.5


