Textbooks/Engineering Programming With Python/Chapter 5Lite (plain text) version
5Modules, objects and data structures
Version 1 · Technically checked (automated checks only) · 4 source lessons · 8 practice items
Introduction
Past a hundred lines, one script becomes a tangle. Modules split a program into files with clear jobs; classes bundle data with the methods that guard it, so a sensor object can keep its own readings and refuse impossible ones. Then pick the right container: a list keeps order, a set answers membership, a dictionary looks up by key, a stack undoes, and a queue serves in arrival order.
Explanation
This chapter is built from 4 School lessons. Each part below is the lesson's own explanation; open the lesson for its predict-and-discover activities.
5.1 One script is not a system
A rover planner works perfectly as one 600-line file. Then you change a unit conversion and three unrelated features break. Why?
A module is just a .py file
Any file units.py is a module called units. Another file in the same folder can write import units and call units.cm_to_m(250), or from units import cm_to_m to use the name directly. Python searches the folder of the script you ran first, then the standard library and installed packages.
Interfaces, not internals
Each module should expose a few functions or classes (its interface) and keep its helpers private. By convention, a name starting with an underscore, such as _clamp, is internal. Other modules use only the interface, so you can rewrite the inside freely as long as the interface and its tests still hold.
Arrows only go one way
Draw an arrow from each module to the modules it imports. Good packages form layers: small utility modules at the bottom, the program's entry point at the top, and no loops. A circular import (A imports B and B imports A) means neither can be loaded or tested on its own; fix it by moving the shared code down a layer or the calling code up.
Common mix-ups
- Splitting code into files makes it slower.
✓ Imports happen once and are cached; the cost is negligible. The benefit is code you can understand, test and change in pieces. - If it runs, the structure doesn't matter.
✓ Structure decides how much breaks when you change something. One-way dependencies keep that blast radius small.
5.2 One blueprint, many sensors
A robot has six identical range sensors, each with its own offset and its own readings. Do you write six sets of variables, or one blueprint?
Class, instance, self
class RangeSensor: defines a new type. front = RangeSensor("front", 2) calls __init__ to build one instance. Inside each method, self is the particular object the method was called on, so self.readings means this sensor's readings.
Attributes live on the object
Assigning self.offset_cm = offset_cm stores a value on that one object; vars(front) shows them. Python looks up an attribute on the object first, then on its class. Constants that every instance shares, like unit = "cm", can sit on the class.
The shared-list trap
A list (or dict) written in the class body exists once, for every instance. Appending through self.readings changes that one shared list, so every sensor sees every reading. Create mutable state inside __init__ so each object gets its own.
Common mix-ups
- self is a keyword that means the class.
✓ self is just the conventional name for the first parameter, which receives the instance the method was called on. - Each object gets its own copy of every class attribute.
✓ Class attributes are shared. Only attributes assigned on self belong to one object.
5.3 List, tuple, set or dict? Pick the right container
Checking whether a part number is in a list of 100,000 parts takes up to 100,000 comparisons. With a set it takes about one. What changed?
Four containers, four questions
list: ordered, indexable, may repeat; 'what is the 5th reading?'. tuple: like a list but fixed, perfect for a record such as (row, col). set: unordered, no repeats; 'is this in the collection?'. dict: keys mapped to values; 'what is the stock of this part?'.
Why sets and dicts are fast
A set or dict computes a hash of the key, which says roughly where to look, so x in s and d[k] take about the same time whether there are 10 items or 10 million (on average). x in some_list compares items one by one: up to n comparisons.
Keys must not change
Only immutable values can be set members or dict keys: numbers, strings and tuples of them. That is another reason to store a cell as the tuple (3, 7) rather than the list [3, 7]. Lists can't be hashed, so {[3, 7]} raises TypeError.
Common mix-ups
- Sets are just lists without duplicates.
✓ Sets are hash tables: unordered, with fast membership tests. That speed is the main reason to use one. - Dicts are slow because they are complicated.
✓ Average dict lookup is about as fast as list indexing and far faster than searching a list.
Open the full lesson: List, tuple, set or dict? Pick the right container →
5.4 Stacks and queues: who goes next?
A robot cell gets jobs faster than it can do them. Do you serve the newest job first, or the oldest? The answer changes everything.
Stack: last in, first out
A Python list is a stack: s.append(x) pushes onto the top, s.pop() removes and returns the top. Both are fast (O(1)). Use it for undo, for backtracking, and for depth-first search.
Queue: first in, first out
from collections import deque gives a double-ended queue. q.append(x) joins the back; q.popleft() serves the front, both in O(1). Don't use list.pop(0) for a queue: it shifts every remaining item, which is O(n).
Empty means stop
Popping from an empty list or deque raises IndexError. Loops usually run while q: (an empty container is falsy), so they end naturally when the work is done.
Common mix-ups
- A list works fine as a queue.
✓ It works, but list.pop(0) is O(n). deque gives O(1) at both ends. - Stacks and queues are different kinds of storage.
✓ They are the same items with different rules about which one leaves next.
Worked examples
One script is not a system: example 1
Split this conversion out of a planner script into its own module, then use it.
Solution
# file: units.py
"""Unit conversions shared by the rover planner."""
CM_PER_M = 100
def cm_to_m(cm):
"""Convert a length in centimetres to metres."""
return cm / CM_PER_Mfrom units import cm_to_m
print(cm_to_m(250)) # 2.5The second file only knows the name cm_to_m and its promise. If you later change how the conversion is done, nothing else needs to change.
One blueprint, many sensors: example 1
Model a range sensor with a calibration offset, record readings and report their mean.
Solution
class RangeSensor:
unit = "cm" # shared by every sensor
def __init__(self, name, offset_cm):
self.name = name
self.offset_cm = offset_cm
self.readings = [] # one list per sensor
def record(self, raw_cm):
self.readings.append(raw_cm + self.offset_cm)
def mean(self):
if not self.readings:
raise ValueError(f"{self.name} has no readings yet")
return sum(self.readings) / len(self.readings)
front = RangeSensor("front", 2)
rear = RangeSensor("rear", -1)
front.record(50)
front.record(54)
rear.record(80)
print(front.mean(), rear.mean()) # 54.0 79.0
print(vars(rear)) # {'name': 'rear', 'offset_cm': -1, 'readings': [79]}List, tuple, set or dict? Pick the right container: example 1
Store visited cells and per-cell costs for a planner.
Solution
visited = set()
cost = {}
start = (3, 0)
visited.add(start)
cost[start] = 0
for cell, c in [((3, 1), 1), ((2, 0), 1), ((3, 1), 1)]:
if cell not in visited: # average O(1), however big visited gets
visited.add(cell)
cost[cell] = c
print(len(visited), cost[(2, 0)], (9, 9) in visited) # 3 1 False
print(cost.get((9, 9), "unreached")) # unreachedStacks and queues: who goes next?: example 1
Process jobs in arrival order and keep an undo history.
Solution
from collections import deque
jobs = deque()
for job in ["drill A", "drill B", "inspect A"]:
jobs.append(job)
print(jobs.popleft()) # drill A (oldest first)
jobs.append("drill C")
print(list(jobs)) # ['drill B', 'inspect A', 'drill C']
undo = []
undo.append("move wp3")
undo.append("delete wp5")
print(undo.pop()) # delete wp5 (newest first)
while jobs: # stops when the queue is empty
print("doing", jobs.popleft())Interactive figures
Interactive figure (online). Description: The dependency explorer shows seven modules in layers: units.py at the bottom; grid.py and report.py import units; io_csv.py and planner.py import grid; main.py imports io_csv, planner and report; test_planner.py imports planner and grid. Changing units.py affects all five modules above it. Ticking the shortcut makes grid.py also import planner.py, creating a circular import.
Interactive figure (online). Description: The inspector shows a RangeSensor class with a front sensor (offset 2 cm) and a rear sensor (offset −1 cm). Recording 50 cm on the front stores 52 in front's own list only. With the bug toggle on, readings live on the class, so the same 52 appears in both sensors' readings.
Interactive figure (online). Description: The dict mode shows an inventory of six parts. Looking up 'servo SG90' returns 6 directly; as a list of pairs a scan would compare 4 names. Looking up an unstocked 'M4 bolt' raises KeyError with square brackets but returns 0 with .get(key, 0); a list scan would check all 6 names.
Laboratory
Everything runs in your browser. No kit, nothing mains-powered. Simulations are simplified educational models.
Studio
Code Lab
Write a Sensor class that stores readings and returns their mean, and test that two sensors do not share data.
Open Code Lab →Nexus project
Nexus: Smart Transportation Junction
Model the cars waiting at a light as a queue and count how many clear in one green phase.
Open Nexus: Smart Transportation Junction →
Guided practice
Answers are checked on the server; wrong answers get a hint and another try. Signed in, solved items also count towards the source lesson.
- units.py defines cm_to_m. Which line lets another file call cm_to_m(250) with no prefix?
- import units
- from units import cm_to_m
- import cm_to_m from units
- include units
- grid.py imports planner.py so GridMap can call bfs, and planner.py imports grid.py. What is the best fix?
- Swap the order of the import lines
- Let main.py call bfs(grid, start, goal), so grid.py no longer imports planner
- Copy bfs into grid.py as well
- Put both files' code into one big file
- Inside record(self, raw_cm), what is self when you call rear.record(80)?
- The RangeSensor class
- The rear object
- The number 80
- A copy of front
- Which class definition gives each sensor its own readings list?
- readings = [] in the class body
- self.readings = [] inside __init__
- global readings
- readings = [] inside record
- You need the stock quantity for any part number, looked up thousands of times. Which container?
- A list of quantities
- A dict {part_no: qty}
- A set of part numbers
- A tuple of tuples, scanned each time
- stock = {'M3-BOLT': 120}. What does stock.get('M4-BOLT', 0) return?
- KeyError
- 0
- None
- 120
- A robot cell queues jobs in arrival order: from collections import deque; q = deque(); q.append(27); q.append(49); q.popleft(); q.append(37); q.popleft(). What value does the final q.popleft() return?
- An editor's undo button should reverse the most recent change first. Which structure?
- A queue
- A stack
- A set
- A dict
Engineering applications
Undo
Every editor's undo button is a stack: each action is pushed, and undo pops the most recent. Print queues, message buffers and robot task lists are queues, served strictly in the order they arrived.
Fleets of sensors
A greenhouse with twenty sensors becomes twenty objects of one class, each with its own calibration and readings. A dictionary keyed by sensor name finds any one of them instantly.
Watch
Optional verified videos. Nothing loads from YouTube until you press play.
- Python OOP Tutorial 1: Classes and Instances (Corey Schafer)
- Data Structures: Stacks and Queues (HackerRank)
- Data Structures: Crash Course Computer Science #14 (CrashCourse)
Chapter summary
- Modules split a program by job; import what you need and keep top-level code minimal.
- A class is a blueprint; each instance keeps its own data, reached through self.
- Choose containers by the question you ask most: order, membership or lookup by key.
- A stack is last in, first out; a queue is first in, first out.
Glossary
- Classes and objects
- A class is a blueprint that bundles data (attributes) and behaviour (methods). Each object made from it has its own copy of the data; self refers to that object inside a method.
- Dictionaries
- A dictionary maps keys to values, as in {"red": 2, "green": 5}, and looks values up by key in roughly constant time.
- Lists and indexing
- A list is an ordered, changeable collection written in square brackets. Items are numbered from 0, and negative indices count back from the end.
- Slicing
- 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.
- List comprehensions
- A list comprehension builds a new list from an existing sequence in one expression: [f(x) for x in items if condition].
Definitions from the Field Guide.
Project: A stores inventory
Model a workshop's parts store as a small package: a Part class, a dictionary from part number to Part, and a queue of incoming orders. Process the orders, report shortfalls, and keep an undo stack so the last change can be reversed.
Deliverables
- Two modules with a clear split of jobs
- Tests for ordering, shortfall and undo
- A paragraph explaining each container choice
Keep your work in your Engineering Journal; it stays private unless you choose to share it.
References
- John V. Guttag (2016). Introduction to Computation and Programming Using Python, 2nd edition. MIT Press.
- Thomas H. Cormen et al. (2009). Introduction to Algorithms, 3rd edition. MIT Press.
- Python Software Foundation. The Python Tutorial. Python Software Foundation. Link ↗
Further reading from the source lessons
- Python tutorial: Modules ↗The official explanation of import, the module search path and packages.
- Python tutorial: Classes ↗The official tour of classes, instances, class and instance variables (including the shared-list trap).
- Python docs: data structures ↗Lists, tuples, sets and dictionaries side by side, with examples.
- Python docs: collections.deque ↗All deque operations and their costs, including maxlen for fixed-size buffers.
Publication record
- Version
- 1
- Status
- Technically checked (automated checks only)
- Technical review
- Automated checks only, last run 2026-11-29. No human, educator or mentor review is claimed.src/content/textbooks/textbooks.test.ts: schema, every lesson, diagram, practice item, video, Field Guide entry, lab and reference resolves; figure numbers recomputed; no practice answers in client payloads.
- Written by
- Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
- Licence
- All rights reserved by the founders unless a licence is approved.
- Corrections
- None recorded yet.Spotted a mistake? Use “Report a problem” on any chapter, or see the corrections page.