Lite / Intelligent Robotic Systems / 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?
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.
Predict
readings = [12, 15, 11, 18, 22, 19, 25, 21]. What is readings[1:6:2]?
- [15, 18, 19]
- [15, 11, 18, 22, 19]
- [12, 11, 22]
- [15, 18, 19, 21]
Guess first, then reveal
[15, 18, 19]: start at index 1 (15), step 2 (index 3 is 18, index 5 is 19), and stop before index 6. The stop index is never included.
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?
What the interactive shows (text version)
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.
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
Intuitive
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.
Technical
Slicing creates a new list (a shallow copy) in time proportional to its length. len(a[s:e]) is max(0, e - s) after clipping to [0, len(a)]. Comprehensions are evaluated left to right like the equivalent for-loop with an if and an append, but are more compact.
Applied
Telemetry tools routinely decimate (keep every n-th sample) to plot long logs quickly, and keep the most recent window (a[-600:] for the last minute at 10 Hz) for live displays.
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.
Practice
Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.
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.
Reflect
Which slicing rule do you expect to trip over most, and what trick will you use to remember it?
Write your answer on paper or in your own notes. Lite never stores what you write.
Go further
- Python tutorial: More on lists
List methods, comprehensions and nested comprehensions.