Foundations to Frontier
Tests
C. Programming, Tools and HPC › C1 Python for Science

Python Language Essentials and Data Structures

The working core of Python for science and engineering: values and names (and why mutable aliasing bites), control flow, comprehensions, slicing, strings and files, and the four built-in containers (list, tuple, dict, set) plus collections (deque, Counter, defaultdict). The emphasis is on choosing the right structure by its cost: hash-based dict and set give O(1) membership, lists give O(1) indexing but O(n) search and front insertion. In the exercises you parse and aggregate a spacecraft telemetry log, then measure the growth exponents of list vs set membership and list vs deque front-insertion.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Labels on boxes, and the right box for the job

A Python program works with values: numbers, text, and collections of other values. A variable is just a name tag tied to a value, not a box that contains it, so two names can point at the same list, and changing it through one name changes what the other sees. Collections come in a few shapes: a list is a numbered shelf, a dict is a labelled filing cabinet, and a set is a bag that remembers only whether something is inside. Picking the right one can make a program a million times faster.

Same job, different container: count the steps
list
1.0e+4 steps
tuple
1.0e+4 steps
set
1 step
dict
1 step
bar length on a log scale · `x in L` scans the list element by element; `x in S` hashes x and jumps straight to its bucket.
look up 7
list scan: 1232571931416→ 4 comparisons
hash set: bucket 7 mod 8 = 7 → [731] → 2 comparisons
A set or dict stores each item in a bucket chosen by its hash, so a lookup only checks that bucket, which stays tiny on average as long as the table is resized as it grows. A list has no such index, so it must look at items one by one. At n = 10⁷ that's the difference between one step and ten million.
Why engineers care

Nearly every robotics and space-software pipeline starts with Python glue: parsing telemetry, configuring experiments, sorting sensor logs. Knowing that x in my_list costs n steps while x in my_set costs one is the difference between a script that processes a day of telemetry in a second and one that takes an hour.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A Python variable is best thought of as…
  2. 2. To check quickly whether an ID is in a large collection, use a…
  3. 3. A dict maps…

Level 1: Beginner

★★☆☆☆ Basic⏱ 25 minSecondary-school mathematics: arithmetic and elementary algebra.

Values, types and names

int (arbitrary precision), float (IEEE-754 double), complex, bool, str (immutable Unicode), bytes and None. Assignment b = a binds a second name to the same object. For mutable objects (lists, dicts, sets) changes through b show up in a. Use a.copy(), list(a) or copy.deepcopy(a) when you need an independent copy.

Control flow and comprehensions

if/elif/else, for x in iterable, while, break/continue, and for … else (the else runs if the loop didn’t break). Comprehensions build containers in one expression:

squares = [x * x for x in range(10) if x % 2 == 0]   # [0, 4, 16, 36, 64]
by_unit = {r["unit"]: r["value"] for r in records}
units = {r["unit"] for r in records}

Slicing

s[start:stop:step] with a half-open interval: s[1:4] takes indices 1, 2 and 3, s[::-1] reverses, and negative indices count from the end. Slices of lists are copies; slices of NumPy arrays are views (C1.5).

The containers

type ordered mutable duplicates lookup by
list yes yes yes position, O(1)
tuple yes no yes position, O(1)
dict insertion order yes unique keys key, O(1) average
set no yes no membership, O(1) average
📝 Quick check (Level 1)
0/3 answered
  1. 1. After a = [1, 2]; b = a; b.append(3), a is…
  2. 2. 'telemetry'[2:5] is…
  3. 3. Which container can be a dict key?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

Costs of common operations (CPython)

operation list deque dict / set
x in c O(n) O(n) O(1) average
append / add O(1) amortized O(1) O(1) average
insert/pop at front O(n) O(1) —
index c[i] O(1) O(n) by key O(1)
sort O(n log n) — —

The collections module

  • Counter(iterable): counts, most_common(k), arithmetic on counts.
  • defaultdict(list): missing keys start as an empty list, which makes grouping natural.
  • deque: fast at both ends, and deque(maxlen=k) gives a ring buffer for sliding windows of sensor data.
  • namedtuple: lightweight records (dataclasses in C1.3 are usually better).

Strings and files

f-strings f"{x:.3f}", str.split/join/strip, and with open(path) as f: for line in f: for streaming line by line without loading the whole file into memory.

🐍 Exercise 1: parse and aggregate a telemetry log
Parse lines like '2026-03-01T00:00:01 IMU OK temp=21.5' into dicts, then count (unit, level) pairs with a Counter, group values by unit with a defaultdict, find the units that reported a given level (a set comprehension), and compute each unit's worst level.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Best structure for a sliding window of the last 100 samples:
  2. 2. defaultdict(list)[key].append(v) on a missing key…
  3. 3. Sorting a list of n items costs…

Level 3: Advanced

★★★★☆ Advanced⏱ 35 minGraduate level, with full derivations and proofs.

How dict and set achieve O(1)

A hash table stores entries in an array of slots. hash(key) picks a slot, and collisions are resolved by probing other slots (CPython uses open addressing with perturbed probing). The table is resized when it is about ⅔ full, keeping the average probe count bounded, so lookups are O(1) on average and O(n) only in adversarial worst cases. That’s why keys must be hashable (immutable with a stable hash), and why equal objects must have equal hashes.

Amortized O(1) append

A list over-allocates: when full, it grows by about 1.125× plus a constant. Copying n elements on each resize costs O(n), but resizes are geometrically spaced, so the total cost of n appends is O(n), O(1) each amortized.

Python’s object model in one paragraph

Everything is an object with an identity (id), a type and a value. Names live in namespaces (local, enclosing, global, builtins: the LEGB rule). Integers and strings are immutable, so “modifying” them makes a new object. Function arguments are passed by object reference: a function can mutate a list you pass in, but rebinding the parameter name doesn’t affect the caller. A classic bug is a mutable default argument, def f(x, acc=[]), which is created once and shared across calls.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Why must dict keys be hashable?
  2. 2. n appends to a list cost in total…
  3. 3. def f(x, acc=[]) is dangerous because…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Complexity, measured

Exercise 2 (best of 3, with the loop count calibrated so each run lasts ≥ 10 ms). Time per operation as n grows from 10³ to 10⁵; typical values over several runs:

operation growth exponent at n = 10⁵ (CPython / Pyodide)
list membership ≈ 1.0 ≈ 210–270 µs / ≈ 940 µs
set membership ≈ 0.0 ≈ 0.005 µs / ≈ 0.02 µs
list.insert(0, …) + pop(0) ≈ 1.0 —
deque.appendleft + popleft ≈ 0.0 —

At n = 10⁵ a set lookup is roughly 40 000–50 000× faster than a list scan. Pyodide (Python compiled to WebAssembly, running in your browser) is 3–4× slower in absolute terms, but the exponents are the same: complexity is a property of the algorithm, not the machine. A first version of this exercise timed only 200 repetitions of the O(1) operations, about 2 µs in total, below the browser’s deliberately coarsened clock, so its exponents came out as noise. Calibrating the loop count fixed that, a useful lesson for any micro-benchmark.

🐍 Exercise 2 (research): measure the complexity of containers
Use timeit to time membership tests (list vs set, worst case) and front insertion (list vs deque) at n = 10³, 10⁴ and 10⁵. Fit log(time) vs log(n) to estimate growth exponents and confirm O(n) vs O(1).

Python in AI, robotics and aerospace

  • Telemetry and log processing: parse, group and count events across subsystems.
  • Configuration and orchestration: dicts and lists (often via YAML/JSON) describe experiments and mission plans.
  • Glue around fast code: Python coordinates NumPy, C++ and CUDA, so keep the Python-level loops on the right data structures.
  • Flight-software tooling: ground-segment scripts, test harnesses and simulators.

References

  1. Python Software Foundation. The Python Language Reference and The Python Standard Library (docs.python.org).
  2. L. Ramalho (2022). Fluent Python, 2nd ed. O’Reilly.
  3. Python Wiki. “TimeComplexity” (wiki.python.org/moin/TimeComplexity).
  4. B. Slatkin (2019). Effective Python, 2nd ed. Addison-Wesley.
  5. T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein (2022). Introduction to Algorithms, 4th ed. MIT Press (ch. 11, hash tables).