liveBook · Manning

Slicing

As explained in Python How-To

Slicing selects or partitions a portion of an indexed sequence or multidimensional array, often along specified indices or dimensions.

Use slicing to retrieve a subsequence from a Python sequence such as a string, list, or tuple. In `sequence[start:stop]`, the start is included and the stop is excluded. section 4.1

Omit the start to begin at the first item, or omit the stop to continue through the end. Add a step to select items at intervals; a negative step processes the sequence from right to left, so use it with care. Although out-of-range slice indices are tolerated, avoid relying on them when they make the intended bounds unclear. section 4.1.1 section 4.1.5

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
 
assert numbers[2:5:2] == [3, 5]                        #1
 
assert numbers[::3] == [1, 4, 7]                       #2
 
assert numbers[::-1] == [9, 8, 7, 6, 5, 4, 3, 2, 1]    #3

These list examples show stepped selection, an omitted start and stop, and reversal. section 4.1.1

A slice object, created with `slice(start, stop, step)`, can be reused to select subsequences. Unlike a `range`, it is not iterable; use ranges for iteration and slices as sequence subscripts. Named slices can clarify repeated selections. Slicing also supports replacing, expanding, shrinking, or removing subsequences in mutable sequences such as lists and bytearrays. section 4.1.2 section 4.1.5 section 4.6

How Python How-To covers it

How deep it goes
Explains bounds, omitted indices, strides, slice objects, and mutable-sequence edits with practical examples.
Examples
Uses fruit and number lists, monthly revenue, and a challenge involving strings, tuples, and ranges.
What it assumes
Introduces sequence types and basic start-and-stop slicing before extending to steps and index variations.
What you can do after
Apply Python slicing to select subsequences with bounds and steps, reuse slice objects, and edit mutable sequences.
How it connects
Connects slicing to Python sequences, indexing, slice objects, ranges, and mutable-sequence operations.

Also explained in

Compare how 16 books explain slicing →

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.