liveBook · Manning

Stride

As explained in Python How-To

A stride is the step interval between successive positions or elements accessed, selected, or processed along a dimension or sequence.

In a Python slice, the stride sets the interval between selected elements: `sequence[start:stop:stride]`. A positive stride selects from left to right; a negative stride selects from right to left. For example, `numbers[::3]` takes every third element, while `numbers[::-1]` reverses the list. section 4.1.1

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

Compare a slice with stride 2, one with stride 3, and a reverse slice. section 4.1.1

Stride also works in list slice assignment. Assigning to `numbers[::2]` replaces every second item in the selected list positions. section 4.1.4

numbers[::2] = [0, 0, 0, 0]
numbers
# output: [0, 1, 0, 16, 0, 18, 0, 20]

See a list updated at every second position through strided slice assignment. section 4.1.4

How Python How-To covers it

How deep it goes
Explains stride in slice notation, positive and negative directions, and list replacement at strided positions.
Examples
Uses list slices to select every third element, reverse a list, and replace every second item.
What you can do after
Apply Python slice notation to select spaced elements or replace selected positions in a list.
How it connects
Connects stride to slicing, sequence indexing, lists, and mutable sequence operations.

Also explained in

Compare how 8 books explain stride →

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.