Programming & Python · Lesson 07
Lists, Tuples & Dictionaries
Est. 35–45 min
Try it · Python in your browser
Run this lesson's example (packets.py), change a number, run it again.
Why
Why packets and buffers need structure
By the end you will pick the right structure, build a small sensor message, and read keys safely.
Concept
The big idea: list vs tuple vs dict
- list: ordered, mutable —
[40.0, 38.5]buffers. - tuple: ordered, immutable —
(distance_cm, clear, side). - dict: key → value —
{"distance_cm": 18.0, ...}. - Index with
buf[-1]; keys withmsg["side"].
How it works
How it actually works, step by step
Choose structure
Growing history → list. Fixed positional packet → tuple. Named fields / JSON → dict.
Fill sample data
3–4 realistic readings.
Compute a summary
latest, average, or key lookup.
Sketch schema
Write field names and units once.
Visual
Visualise it: data structure explorer
Explore how collections hold robot-ish values — buffers vs named fields.
Interactive · Data structure explorer
Ultrasonic ring buffer as a Python list
readings = [12.4,11.9,18.2,9.5,22]
latest = readings[-1] # 22.0
mid = readings[2] # 18.2
min = 9.5
max = 22.0
avg = 14.80
# robotics: rolling window for filtersCode lab
Code lab: packets
#!/usr/bin/env python3
"""Lists, tuples, dicts as sensor packets."""
# list — growing buffer of recent distances (cm)
buffer = [40.0, 38.5, 22.0]
buffer.append(18.0)
print("buffer:", buffer)
print("latest:", buffer[-1], "avg:", round(sum(buffer) / len(buffer), 2))
# tuple — fixed packet shape (immutable)
packet = (18.0, True, "front") # distance_cm, clear, side
print("packet tuple:", packet)
# dict — named fields (JSON-friendly)
msg = {
"distance_cm": 18.0,
"clear": True,
"side": "front",
"ts_ms": 1200,
}
print("msg keys:", sorted(msg.keys()))
print(f"side={msg['side']} distance_cm={msg['distance_cm']}")Expected output
buffer: [40.0, 38.5, 22.0, 18.0] latest: 18.0 avg: 29.62 packet tuple: (18.0, True, 'front') msg keys: ['clear', 'distance_cm', 'side', 'ts_ms'] side=front distance_cm=18.0
Real world
Where structures show up in the lab
- Ring buffers of IMU samples.
- ROS-like dict messages before full middleware.
- Config dictionaries for thresholds.
Mistakes
Common mistakes and confusions
Hardware & safety
Hardware lab and safety notes
Sensor packets are just data structures. Log five real (or pretend) distance readings into a list, then package one as a tuple and as a dict — exactly what you will send over serial or ROS 2 later.
- List: a growing buffer of the last N readings.
- Tuple: a fixed packet
(distance_cm, clear, side). - Dict: named fields, ready to become JSON in Lesson 10.
Debugging
Debugging: when it doesn’t work
| Symptom | Likely cause | Fix |
|---|---|---|
KeyError: 'side' | Field missing in a noisy message | Use msg.get("side", "unknown") |
TypeError: 'tuple' object does not support item assignment | Tuples are immutable | Build a new tuple |
IndexError: list index out of range | Empty buffer | Check if buffer: first |
| Average looks wrong | Integer and string readings mixed | Convert every reading to float |
Think
Think about it
Think
When is a tuple better than a list for a packet?
Experiment
Try it in the lab: packet design
Experiment
Packet design
- Run packets.py; confirm avg ≈ 29.62.
- Add another distance to the buffer; recompute avg.
- Design a dict with distance_cm, clear, side, ts_ms.
- Open the data-structure explorer and mirror your fields conceptually.
Interactive · Data structure explorer
Ultrasonic ring buffer as a Python list
readings = [12.4,11.9,18.2,9.5,22]
latest = readings[-1] # 22.0
mid = readings[2] # 18.2
min = 9.5
max = 22.0
avg = 14.80
# robotics: rolling window for filtersKnowledge check
Check your understanding
Knowledge check
1. Which is mutable?
2. JSON-friendly named fields map best to…
3. buf[-1] means…
4. In the lab output, side was…
5. append on a list…
Practice quiz
Coding practice
Mini assignment
Hands-on assignment
Mini assignment
Message schema
Define a sensor message as dict + an equivalent tuple. Document field units.
Deliverables
- schema.md or comment block
- packets_custom.py printing both forms
Do this, step by step
- Run
packets.py; check the average 29.62 cm. - Append 15.0 to the buffer and predict the new average.
- Keep only the last 3 readings with
buffer[-3:]. - Write
packets_custom.py: one dict and the same data as a tuple, with units documented.
Stuck? Hints, one at a time
- Hint 1: (40.0 + 38.5 + 22.0 + 18.0) / 4 = 29.625, printed as 29.62.
- Hint 2: Adding 15.0 gives 133.5 / 5 = 26.7.
- Hint 3: Use a dict when fields have names; use a tuple only when the order is fixed and documented.
Challenges (pick by level)
- 🟢 Easy: Print the smallest reading with
min(). - 🟡 Medium: Use
collections.deque(maxlen=5)as a rolling buffer. - 🟠 Hard: Convert a list of tuples into a list of dicts with a loop.
Next step
Next, Lesson 8: Objects & Classes. Related: messages and topics in Stage 10 — ROS 2.
Sources
Self-attested for now — keep artifacts in your lab notebook.
Complete
Today's goal
0 of 1 done today
Mark this lesson complete when you have worked the experiment, knowledge check, and assignment (even roughly).