Skip to content
Tactiverge

School/○ Innovator/Week 3

Slice, filter, transform: lists at speed

A wheel encoder logs 10,000 speeds. You need the last minute, every tenth sample, and only the readings above 20 cm/s. Can you do each in one line?

About 35 min · 3 goals · Checked by automated tests

1.Why should I care?

Sensor logs, part lists and paths are all lists. Slicing and comprehensions let you say exactly which part of the data you want, in a line that is easy to read and hard to get subtly wrong.

  • ◇ Index and slice lists with positive and negative indexes and a step, predicting results exactly.
  • ◇ Filter and transform lists with comprehensions.
  • ◇ Explain why a slice's stop index is excluded and use that to avoid off-by-one errors.

2.Discover

In List + slicing mode, predict each result before you type it: readings[2:5], readings[-3:], readings[::3], readings[::-1], readings[5:1:-2]. Then try a step of 0. Which prediction did you get wrong, and why?

Loading the interactive…

Can't use the interactive? Read a description instead

The list visualiser shows readings = [12, 15, 11, 18, 22, 19, 25, 21] with each index from 0 to 7 (and −8 to −1). Typing start, stop and step highlights the chosen items: 1, 6, 2 selects 15, 18 and 19; a negative step walks backwards; a step of 0 gives a ValueError.

3.Checkpoint: guided practice

Check what you just discovered before going on. Hints appear after a wrong answer.

Practice 1 · a fresh version every time

A wheel encoder log is readings = [1, 53, 98, 96, 28, 61, 72, 43, 99]. What does sum(readings[3:4]) evaluate to?

4.Predict

readings = [12, 15, 11, 18, 22, 19, 25, 21]. What is readings[1:6:2]?

Guess first. Being wrong here is how the surprise works.

5.Understand

Indexes count gaps, from zero

readings[0] is the first item, readings[-1] the last. A slice a[start:stop] includes start and stops before stop, so a[0:3] has exactly 3 items and a[:k] + a[k:] is always the whole list. Out-of-range slice ends are clipped, but out-of-range single indexes raise IndexError.

Steps and reversing

A third number is the step: a[::10] is every tenth sample (decimation), a[::-1] is the list reversed. With a negative step the defaults flip: start from the end and walk backwards. A step of 0 is an error.

Comprehensions

[v for v in readings if v > 20] filters; [v / 100 for v in readings] transforms (cm/s to m/s); you can do both at once. A comprehension builds a new list and leaves the original untouched, which makes it safer than editing a list while looping over it.

Explain it another way

Think of fence posts with the gaps numbered: a slice [2:5] takes the fence panels between post 2 and post 5. That's 5 − 2 = 3 panels.

Worked example 1

From a 10 Hz speed log in cm/s, take the last 2 seconds, convert to m/s and keep only readings above 0.2 m/s.

readings = [12, 15, 11, 18, 22, 19, 25, 21, 30, 28, 24, 26, 18, 27, 31, 29, 33, 20, 35, 34, 32, 36]
last_2_s = readings[-20:]                      # 10 Hz × 2 s = 20 samples
in_m_s = [v / 100 for v in last_2_s]
fast = [v for v in in_m_s if v > 0.2]
print(len(last_2_s), len(fast), fast[:3])      # 20 15 [0.22, 0.25, 0.21]

Common mix-ups

  • a[2:5] contains the items at indexes 2, 3, 4 and 5.
    ✓ The stop index is excluded: 2, 3 and 4 only.
  • Slicing past the end raises an error.
    ✓ Slice ends are clipped to the list. Only single-item indexing raises IndexError.

6.Practice on your own

Practice, not a test. Wrong answers get a hint and another try.

Practice 2

A log has 3,000 samples at 50 Hz. Which slice gives the last 10 seconds?

Practice 3

Which comprehension gives the masses (kg) of parts heavier than 0.5 kg, from masses_g in grams?

Practice 4 · a fresh version every time

A wheel encoder log is readings = [67, 75, 95, 45, 62, 53, 2, 53]. What does len(readings[0:5:2]) evaluate to?

Practice 5

path has 8 waypoints. Which expression raises IndexError?

7.Apply it

Write a function window_stats(readings, rate_hz, seconds) that returns the min, mean and max of the most recent window. Test it on a short list where you can work the answer by hand, including a window longer than the log.

8.Reflect

9.Go further

Concepts: Lists, dictionaries and tabular data