Skip to content
Tactiverge

Python reference

Slicing

Also called: [start:stop:step] · sublist · slice · reverse a list

Definition

A slice seq[start:stop:step] takes items from start up to but not including stop, moving step at a time; any part can be left out.

Picture it

The stop index is exclusive, so data[0:3] is three items and data[3:6] carries on with no overlap. data[-5:] is 'the last five samples', perfect for a moving window. data[::-1] reverses.

The maths

number of items in seq[a:b] = b − a (for 0 ≤ a ≤ b ≤ len)
SI units used in this entry
QuantityUnitSymbol
ratiodimensionless1

Worked example

data = [0, 10, 20, 30, 40, 50, 60]. What are data[2:5], data[-3:], data[::3] and len(data[1:6])?

  1. Indices 2, 3, 4 → [20, 30, 40]
  2. Last three → [40, 50, 60]
  3. Every third from 0 → [0, 30, 60]
  4. 6 − 1 = 5 items

Answer[20, 30, 40], [40, 50, 60], [0, 30, 60] and 5.

✓ The number in this answer is recomputed from scratch by an automated test.

In Python

window = samples[-5:]           # last five readings
smoothed = sum(window) / len(window)

Common misconceptions

  • Misconception: Slices never raise IndexError: data[5:100] just stops at the end.
  • Misconception: A slice of a list is a new list; changing it does not change the original.