liveBook · Manning

Slice object

As explained in Python Workout, Second Edition

A slice is a Python specification of start, stop, and step bounds for selecting elements from a sequence or other sliceable object.

A slice specifies a sequence’s start, stop, and optional step bounds. Python uses the colon form inside square brackets to retrieve a subset, stopping before the final index. section 3.3 section 4.3

Use slices to control which sequence elements are selected:

  • Write sequence[start:stop] for a contiguous range. section 4.3
  • Add a third value—sequence[start:stop:step]—to skip elements. section 3.3
  • Omit the start or stop to begin at the sequence’s first element or continue to its end. section 3.3 section 4.3
  • Expect a slice to preserve the sequence type: lists produce lists, tuples produce tuples, and strings produce strings. section 4.3
  • Rely on forgiving bounds when a slice extends beyond the sequence; Python truncates the result rather than raising an error. section 4.3

Select every other character

s = 'abcdefgh' print(s[2:6:2]) # ce print(s[::2]) # aceg Use mylist[-n:] with a for loop to process only the final n elements of a list. section 3.3 section 4.5

Use a slice as a loop range

def mysum(items): if not items: return 0 output = items[0] for item in items[1:]: output += item return output The items[1:] expression skips the base element and remains safe when only one item is supplied, because the resulting slice is empty. section 4.7

s = 'abcdefgh'
print(s[2:6:2])    #1

Trace how a start, stop, and step select alternating elements from a string. section 3.3

How Python Workout, Second Edition covers it

How deep it goes
Explains bounds, steps, result types, forgiving limits, and loop applications, but does not descend into slice-object internals.
Examples
Uses stepped strings, final-list-element selection, tuple and list slices, and a summation loop over items[1:].
What it assumes
Assumes familiarity with Python sequences, numeric indexes, square-bracket access, and for loops.
What you can do after
Apply slices via Python sequence syntax to retrieve ranges, skip elements, handle edges, and iterate over selected data.
How it connects
Connects slicing with sequence indexing, strings, lists, tuples, dynamic typing, and for loops.

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 Workout, Second Edition. The section links point to the parts of the book it draws on.