liveBook · Manning

Slice object

As explained in Python How-To

A slice object is a Python object that represents the start, stop, and step parameters for selecting elements from a sequence.

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

How Python How-To covers it

How deep it goes
Explains construction, attributes, indexing, named reuse, range differences, and mutable-sequence surgery, including strided assignment.
Examples
Uses odd-number selection, named task-field slices, fixed-width records, strided replacement, and subsequence deletion.
What it assumes
Assumes familiarity with Python sequences and indexing while teaching slice construction, range differences, and mutable-sequence behavior.
What you can do after
Apply it via Python sequence subscripting, named fixed-width parsing, and mutable-list replacement or deletion.
How it connects
Connects sequence slicing with ranges, mutable sequences, immutable sequences, and fixed-width text parsing.

Also explained in

Compare how 3 books explain slice object →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.