Stage 02 · Lesson 07/15

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 with msg["side"].

How it works

How it actually works, step by step

  1. Choose structure

    Growing history → list. Fixed positional packet → tuple. Named fields / JSON → dict.

  2. Fill sample data

    3–4 realistic readings.

  3. Compute a summary

    latest, average, or key lookup.

  4. 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 filters

Code lab

Code lab: packets

packets.py · Python
#!/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
SymptomLikely causeFix
KeyError: 'side'Field missing in a noisy messageUse msg.get("side", "unknown")
TypeError: 'tuple' object does not support item assignmentTuples are immutableBuild a new tuple
IndexError: list index out of rangeEmpty bufferCheck if buffer: first
Average looks wrongInteger and string readings mixedConvert every reading to float
NoteRead the last line of a Python error first — it names the problem — then the line number above it. Change one thing at a time and re-run.

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

  1. Run packets.py; confirm avg ≈ 29.62.
  2. Add another distance to the buffer; recompute avg.
  3. Design a dict with distance_cm, clear, side, ts_ms.
  4. 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 filters

Knowledge 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

Loading practice quiz…

Coding practice

Loading coding exercises…

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

  1. Run packets.py; check the average 29.62 cm.
  2. Append 15.0 to the buffer and predict the new average.
  3. Keep only the last 3 readings with buffer[-3:].
  4. Write packets_custom.py: one dict and the same data as a tuple, with units documented.

Stuck? Hints, one at a time

NoteTry the task first. Read one hint, try again, and only then read the next one.
  1. Hint 1: (40.0 + 38.5 + 22.0 + 18.0) / 4 = 29.625, printed as 29.62.
  2. Hint 2: Adding 15.0 gives 133.5 / 5 = 26.7.
  3. 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

0-day streak
Daily goal:lessons, quizzes or assignments a day

Mark this lesson complete when you have worked the experiment, knowledge check, and assignment (even roughly).

Stuck somewhere?

Ask a doubt about this lesson

Saved with this lesson's id and your email so we can reply. Privacy · or email contact@aihubstation.in