DS 208 · Week 3

Data Structures & Files

Holding many values at once — lists, tuples, sets and dictionaries — then reading and writing real files, up to and including CSV.

Programming for Data Science · University of the Philippines Cebu

Outline

From single values to collections and files

A

Lists

Order, slices, sorting, and aliasing

B

Tuples & sets

Fixed records and uniqueness

C

Dictionaries

Lookups, tallies and nested data

D

Files & CSV

Read, clean, compute, write back

Previous session

Limits of single values

Week 2 covered a value, a choice, a function. Real data, however, comes in bulk: thousands of rows. This requires containers and a way to load them.

A container is a value that holds other values — one variable, many items inside.

The four containers

Lists and dictionaries do most of the work; tuples and sets fill two specific gaps.

The missing piece

Loading data in from a file instead of typing it into cells.

About the tool

CSV has been in use for more than fifty years

1972

IBM Fortran

A compiler reads and writes values separated by commas.

1983

The name

“Comma-separated value” appears in a spreadsheet manual.

2003

Python’s csv module

Added to the standard library in Python 2.3.

2005

RFC 4180

The first written standard, and the official text/csv file type.

SourceWikipedia: Comma-separated values; PEP 305

About the tool

Where CSV files are used

SourceWikipedia: Comma-separated values; course dataset: DPWH flood control projects, CC0, n = 34,079

Key terms

Ten terms for collections and files

In Week 2, each variable held one value: a number, a string, a boolean. This week’s terms concern containers (values that hold other values) and about reading data from files.

list

An ordered collection of values in square brackets. It can be changed later.

e.g. [3, 5, 4]

index

An item’s position number, counted from 0. Analogy: seat numbers starting at zero.

e.g. in ["a", "b"], "b" is at index 1

slice

A run of items taken by position: from the start index up to, not including, the stop.

e.g. [10, 20, 30][0:2] is [10, 20]

method

A function that belongs to a value, called with a dot after the value.

e.g. names.append("Ana")

tuple

An ordered collection in round brackets that cannot be changed once made.

e.g. a coordinate (10.3, 123.9)

set

An unordered collection in curly brackets that keeps only one of each value.

e.g. set(["yes", "no", "yes"]) is {'yes', 'no'}

dictionary (dict)

A collection of key → value pairs. Analogy: a phone book maps a name to a number.

e.g. {"Cebu": 964000, "Davao": 1777000}

key

The label used to look up a value in a dictionary. Each key appears once.

e.g. pop["Cebu"] uses the key "Cebu"

file path

The address of a file on disk. A bare name means “in the current folder”.

e.g. "grades.csv" or "data/grades.csv"

CSV

A plain-text table: one row per line, commas between the columns, often a header row first.

e.g. name,score then Ana,88

Part A

Lists

Ordered collections accessed by position.

Lists appeared briefly in Week 2’s loops. This part covers access by position, slicing and sorting, and one common error: aliasing.

Indexing

Indexes start at 0

A list is an ordered collection of values in square brackets. Each item has an index: its position number. The first item is [0], not [1]. Negative indexes count from the end, so [-1] is always the last item.

cities = ["Cebu", "Davao", "Iloilo", "Baguio"] print(cities[0]) print(cities[-1]) # the last one print(len(cities)) Cebu Baguio 4
  • cities = [...]a list of four strings, stored under the name cities
  • cities[0]square brackets after a list mean “the item at this index”: "Cebu"
  • cities[-1]count from the end: the last item, "Baguio"
  • len(cities)how many items: 4. So the last index is 4 - 1 = 3
Conceptual model

Positive and negative indexes

"Cebu" "Davao" "Iloilo" "Baguio" 01 23 -4-3 -2-1 index from the start → ← index from the end
Exercise · 3 min

Positions from both ends

Index 0 is the first item; index −1 is the last.

Tasks

  1. Predict what cities[1] and cities[-2] are.
  2. Select ▶ Run / Edit and run the code.
  3. Change cities[1] to cities[4]. What does the error say?

Result on the lecture laptop (select to reveal)

Davao Iloilo. cities[4] stops with IndexError: list index out of range: four cities have indexes 0 to 3.

cities = ["Cebu", "Davao", "Iloilo", "Baguio"] print(cities[1], cities[-2])
List operations

Common list operations

OperationCodeResult on [3, 5]
Add to the endnums.append(9)[3, 5, 9]
How manylen(nums)2
Membership test5 in numsTrue
Sum themsum(nums)8
Visit each itemfor n in nums:3, then 5
Common error

Two names can share one list

b = a does not copy the list — it gives the same list a second name, an alias. A change through either name affects "both", because there is only one list.

b = a is a second key to the same house, not a second house; moving furniture with either key changes the one house. .copy() builds a second house.

a = [3, 5, 9] b = a # same list, new name b.append(99) print(a) # a changed too! c = a.copy() # an actual second list c.append(7) print(a, c) # a is untouched [3, 5, 9, 99] [3, 5, 9, 99] [3, 5, 9, 99, 7]

The rule

An independent copy must be requested explicitly: .copy() (or list(a)).

Sorting

sorted() returns; .sort() rearranges

Two tools with one important difference: sorted(x) hands back a new sorted list; x.sort() reorders the original in place (it changes the list itself rather than making a new one) and returns None.

temps = [31.2, 28.5, 33.1, 29.9] print(sorted(temps)) print(sorted(temps, reverse=True)[:2]) # top two: a classic move print(temps) # unchanged [28.5, 29.9, 31.2, 33.1] [33.1, 31.2] [31.2, 28.5, 33.1, 29.9]

Common error

x = x.sort() sets x to None. Only one of the two tools should be used at a time.

  • sorted(temps)a new list, smallest to largest; temps itself is untouched
  • reverse=Truea keyword argument: sort largest first instead
  • [:2]slice with no start = “from the beginning”: the first two items, i.e. the top two
Strings ↔ lists

split separates; join combines

A line of text becomes a list of pieces with .split(); a list becomes one string with .join(). This pair connects files and containers, and is used again in Part D.

line = "Cebu,964000,Visayas" parts = line.split(",") print(parts) print(repr(parts[1])) # a string, not a number yet! print(" | ".join(["a", "b", "c"])) ['Cebu', '964000', 'Visayas'] '964000' a | b | c

Note

split is called on the string; join on the separator (the text placed between pieces, here "," or " | "). This is a frequent source of error. The quotes in '964000' say it is still a string.

Exercise · 3 min

Text that looks like a number

split returns text, even for the digits.

Tasks

  1. Predict what parts[1] * 2 prints.
  2. Select ▶ Run / Edit and run the code.
  3. Change it to int(parts[1]) * 2. Predict, then run.

Result on the lecture laptop (select to reveal)

964000964000: text times 2 repeats it. With int(...) it doubles the number: 1928000.

parts = "Cebu,964000,Visayas".split(",") print(parts[1] * 2)
Review question

Question (select to reveal the answer)

Given nums = [10, 20, 30, 40], what does nums[1:3] return?

A · [10, 20, 30]
B · [20, 30]
C · [20, 30, 40]
D · [10, 20]

B — [20, 30].

Start at index 1 (20), stop before index 3 (40). The stop index is never included, so the slice has 3 − 1 = 2 items.

Part B

Tuples & sets

Two smaller containers, each with one specific purpose.

Part A covered lists: ordered and changeable. Each container in this part deliberately omits one list feature — a tuple cannot change; a set has no order and no duplicates.

Definition: tuple

Tuples: lists that cannot change

A tuple uses round brackets instead of square. Indexing and slicing work exactly as for a list, but it is immutable (cannot be changed after it is made), so any attempt to modify it raises an error. This rigidity is intentional.

Reading this error

Last line
TypeError: this type (a tuple) does not allow that operation
The message
“item assignment” = changing one item with point[0] = …
Check first
whether a list, or a new tuple, is needed instead
# fails on purpose: read the last line point = (10.3157, 123.8854) # Cebu City print(point[0]) point[0] = 5 10.3157 TypeError: 'tuple' object does not support item assignment

Typical use

Fixed-shape records: a coordinate, an (R, G, B) colour, a (name, score) pair. Each position has a fixed meaning.

Unpacking

Unpacking: several names in one line

Unpacking: assign a tuple to comma-separated names and Python hands out the values in order — the first to lat, the second to lon. This is used throughout Part C: a dictionary’s .items() gives (key, value) tuples. (tally below is the vote-count dictionary built in Part C.)

point = (10.3157, 123.8854) lat, lon = point print(lat) # you've been unpacking all along: tally = {"yes": 3, "no": 2} for k, v in tally.items(): print(k, v) 10.3157 yes 3 no 2

Counts must match

Two names need exactly two values — otherwise ValueError: too many/not enough values to unpack. A ValueError means the type was right but the value did not fit (here: the wrong number of items).

Definition: set

Sets: unordered collections of unique values

A set: curly brackets, no duplicates, no positions. It is the preferred tool for two tasks: dedup (removing duplicates) and fast membership tests (checking whether a value is present).

votes = ["yes", "no", "yes", "yes", "no"] print(sorted(set(votes))) # a set has no order; sorted() gives one print(len(set(votes))) # distinct answers print("maybe" in set(votes)) ['no', 'yes'] 2 False
  • set(votes)make a set from the list: each answer kept once. No index, so the order may vary
  • len(set(votes))how many different answers: 2
  • "maybe" in set(votes)whether "maybe" is one of them: False

Example: distinct counts

The number of distinct cities in a column is len(set(column)), in one line.

Set operations

Set algebra for data questions

QuestionOperator{1,2,3} vs {3,4}
In either group (union)A | B{1, 2, 3, 4}
In both groups (intersection)A & B{3}
In A but not B (difference)A - B{1, 2}
Summary

Four containers and their uses

ContainerLooks likeOrderedChangeableTypical use
list[1, 2, 2]YesYesthe items, in order
tuple(10.3, 123.9)YesNoa fixed-shape record
set{1, 2}NoYesuniqueness & membership
dict{"a": 1}InsertionYeslookup by name
Review question

Question (select to reveal the answer)

A column of 500 barangay names has duplicates. Which expression counts the distinct barangays?

A · len(names)
B · len(set(names))
C · set(len(names))
D · sorted(names)[0]

B — len(set(names)).

set() collapses duplicates; len() counts what remains. A gives 500 (rows, not barangays); C is reversed and errors; D is only the alphabetically first name.

Break

  Ten minutes

Next: dictionaries, nested data and real files.

Part C

Dictionaries

Values accessed by key, not by position.

Lists and tuples find things by position. This part adds the dictionary, which finds things by name and then places containers inside containers, which is the structure of real datasets.

Dictionaries

Access by name instead of position

When "the third item" is meaningless but "Davao's population" is the required value, a dictionary is appropriate. Each entry is a key : value pair: the key is the label that is looked up, the value is what is returned.

A phone book, where a name (the key) is looked up to find a number (the value), not “the 3rd entry”.

pop = { "Cebu": 964_000, "Davao": 1_777_000, } print(pop["Davao"]) pop["Baguio"] = 366_000 # add a key print(pop) 1777000 {'Cebu': 964000, 'Davao': 1777000, 'Baguio': 366000}
  • pop = { … }curly brackets with key: value pairs make a dictionary
  • 964_000the underscores are only for human readers: Python reads 964000
  • pop["Davao"]look up the value stored under the key "Davao": 1777000
  • pop["Baguio"] = 366_000a new key: adds the pair. (An existing key would be overwritten.)
Definition

Definition: mapping (a dictionary)

Mapping (Python Standard Library)

“A mapping object maps hashable values to arbitrary objects.” The dictionary is Python’s standard mapping type.

Part of the definitionIn pop
hashable values: the keys, each unique"Cebu", "Davao", "Baguio"
arbitrary objects: the values964000, 1777000, 366000
maps: one value per key, found by the keypop["Davao"] gives 1777000; no position needed

Source: Python Standard Library documentation, “Mapping Types — dict”.

Lists and dictionaries

Access by position versus label

ListDictionary
Reach an item byposition: x[0]key: x["Cebu"]
Order significantYes; it is a sequenceInsertion order kept, rarely used
Best when"the items, in order""look this up by name"
Missing itemIndexErrorKeyError (or .get)
Missing keys

[] raises an error; .get() returns a default

Requesting a missing key raises KeyError. When gaps are expected, as in most real data, .get() returns a default instead.

# fails on purpose: read the last line pop = {"Cebu": 964_000, "Davao": 1_777_000} print(pop.get("Manila")) # None: no error print(pop.get("Manila", 0)) # 0: a default of our choosing pop["Manila"] # [] has no default None 0 KeyError: 'Manila'

Reading this error

Last line
KeyError: 'Manila' — the dictionary has no key 'Manila'; the message is the missing key
Check first
spelling and capitals: "manila" and "Manila" are different keys
.get(key, default)
a method that returns the default (or None) instead of stopping
Counting pattern

Counting occurrences with a dictionary

A dictionary maps each distinct item to a running count. This pattern underlies word counts, vote counts and category frequencies.

votes = ["yes", "no", "yes", "yes"] tally = {} for v in votes: tally[v] = tally.get(v, 0) + 1 print(tally) {'yes': 3, 'no': 1}
  • tally = {}start with an empty dictionary
  • for v in votes:one pass per vote; v is "yes", then "no"…
  • tally.get(v, 0) + 1the count so far for this vote (0 if it is new), plus one
  • tally[v] = …store the new count under that key
  • {'yes': 3, 'no': 1}the result: three yes votes, one no
Exercise · 3 min

A tally of new answers

The same counting loop, on six votes with a new answer in them.

Tasks

  1. Predict the tally.
  2. Select ▶ Run / Edit and run the code.
  3. Add "maybe" to the list twice. What changes in the output?

Result on the lecture laptop (select to reveal)

{'yes': 3, 'no': 2, 'abstain': 1}. With two "maybe" a fourth key appears, 'maybe': 2: the loop needs no change.

votes = ["yes", "no", "yes", "yes", "abstain", "no"] tally = {} for v in votes: tally[v] = tally.get(v, 0) + 1 print(tally)
Iterating over a dictionary

Iterating over keys, values or both

LoopGivesUse when
for k in d:each keyonly the labels are needed
for v in d.values():each valueonly the numbers are needed
for k, v in d.items():both at oncethe pair is needed (the common case)
Review question

Question (select to reveal the answer)

A loop for x in scores: runs over a dictionary scores. What does x hold each time?

A · The values
B · The keys
C · (key, value) pairs
D · An error

B — the keys.

Looping a dict directly gives its keys. For the values use .values(); for both use .items(). Assuming the loop gives values is a very common bug.

Nested data

Datasets as containers inside containers

Nested data · access

Chained brackets, from outside to inside

Each bracket removes one layer. students[0] is a dict; ["name"] reaches into it. Chains are read left to right, one layer at a time.

A postal address, first the building (students[0]), then the room inside it (["name"]).

print(students[0]) print(students[0]["name"]) print(scores["A"][1]) # list scores["A"], then index 1 {'name': 'Ana', 'section': 'A', 'score': 88} Ana 91

Debugging guideline

For deeply nested data, print one layer at a time: print(x), then print(x[0]), then print(x[0]["name"]).

Nested data · loops

Filtering and finding the maximum by hand

Loop over the rows; each pass holds one dict. Every filter, tally and maximum question is a variant of this loop. (The grey lines show what the variables hold afterwards.)

  • for s in students:s is one student’s dict each time round
  • s["score"] >= 80whether that student’s score is at least 80
  • top = students[0]start by assuming the first student is the best
  • top = sa higher score was found: store this student instead
# who passed? passing = [] for s in students: if s["score"] >= 80: passing.append(s["name"]) print(passing) # who's top? top = students[0] for s in students: if s["score"] > top["score"]: top = s print(top["name"], top["score"]) ['Ana', 'Carla'] Carla 91
Nested data · grouping

Building a dict of lists in a loop

An extension of the tally pattern: instead of counting per key, values are collected per key. A new key starts an empty list; values are then appended.

by_section = {} for s in students: sec = s["section"] if sec not in by_section: by_section[sec] = [] # start the list by_section[sec].append(s["score"]) print(by_section) {'A': [88, 91], 'B': [74]}

Connection to group-by

pandas' df.groupby("section") performs this loop internally.

  • if sec not in by_section:checks whether this section is new (in on a dict checks its keys)
  • by_section[sec] = []then give it an empty list to fill
  • by_section[sec].append(…)add this student’s score to their section’s list
Part D

Files & CSV

Reading data from disk instead of typing it into a cell.

So far every value was typed into the code. Parts A–C covered containers; this part fills them from files on disk and writes results back out.

Open, read, close

A file is read line by line

A file is named data saved on disk; its file path is its address. "hours.txt" alone means “in the current folder”; "data/hours.txt" means “inside the data folder”. A loop over an open file gives one line per pass. The with block closes the file automatically when it ends, even if an error occurs.

with open("hours.txt") as f: for line in f: print(repr(line)) '12\n' '7\n' '0\n'
  • open("hours.txt")open the file for reading; a wrong path gives FileNotFoundError
  • with … as f:call the open file f inside the indented block; close it at the end
  • for line in f:one line of text per pass — always a string
  • repr(line)show the string with its hidden characters: \n is the end-of-line mark
Newline characters

Every line ends in \n

Each line carries an invisible newline character, written \n: the mark that says “the line ends here”. repr() reveals it. If it is left in, comparisons and conversions fail without visible cause. .strip() removes whitespace (spaces, tabs, newlines) from both ends.

line = "12\n" print(int(line)) # int is forgiving print(line == "12") # False! (the \n) print(repr(line.strip())) # clean 12 False '12'

Guideline

Apply .strip() to every line when reading. Whitespace should be removed before the text is used.

Synthesis

Reading a file and computing a summary

Strip each line, convert it to a number, accumulate. This short loop is the basic structure of every data-loading script.

  • total = count = 0start both at 0 in one line
  • if not line: continuean empty string is falsy; continue = skip the rest of this pass, go to the next line
  • total += int(line)turn the text into a number and add it (+= means total = total + …)
  • print(total / count)the average of the non-blank lines
total = count = 0 with open("hours.txt") as f: for line in f: line = line.strip() if not line: continue # skip blanks total += int(line) count += 1 print(total / count) 6.333333333333333
Cleaning while reading

Common irregularities in real files

Writing files

Writing with mode "w" and its risk

Open with a mode string, which states the intended operation: "r" reads (the default), "w" erases and rewrites the file; "a" appends to the end. Newlines must be added explicitly; write() does not add them.

with open("report.txt", "w") as f: f.write("Mean hours: 6.3\n") f.write("Rows used: 3\n") # "a" adds to the end instead: with open("log.txt", "a") as f: f.write("run finished\n") print(open("report.txt").read(), end="") Mean hours: 6.3 Rows used: 3

Common error

open("data.txt", "w") empties the file the instant it runs — before any write. Raw data files should never be opened in "w".

Structured lines

From lines to columns with split

Real data files have several values per line, separated by commas: a CSV file (comma-separated values). The first line is usually the header row — the column names. Part A's .split(",") turns each line into a list — a row.

# grades.csv, line by line with open("grades.csv") as f: for line in f: print(line.strip()) line = "Ana,A,88" parts = line.strip().split(",") print(parts) score = int(parts[2]) # strings until you convert name,section,score Ana,A,88 Ben,B,74 Carla,A,91 Diego,B,82 Elena,A,67 ['Ana', 'A', '88']
Definition

Definition: CSV (RFC 4180)

Comma-separated values, the standard’s rules (Shafranovich, 2005)

Each record is on a separate line. Fields are separated by commas. Fields containing line breaks, double quotes or commas should be enclosed in double quotes.

LineFields, by the rules
Ana,A,883: Ana, A, 88
"Reyes, Jr.",A,903: the quoted Reyes, Jr. keeps its comma

split(",") knows only the second rule; the csv module follows all three, as the next slide shows.

Source: Shafranovich (2005), RFC 4180: Common Format and MIME Type for Comma-Separated Values (CSV) Files, IETF.

The csv module

split(",") fails on real CSVs

When a value itself contains a comma, simple splitting breaks the row apart. CSV’s quoting rule: a value containing a comma is wrapped in double quotes. The csv module — a file of ready-made code that comes with Python, loaded with import csv — knows all the rules. next(...) takes the first row the reader produces.

line = '"Reyes, Jr.",A,90' print(line.split(",")) # 4 pieces: wrong import csv print(next(csv.reader([line]))) # 3 pieces: correct ['"Reyes', ' Jr."', 'A', '90'] ['Reyes, Jr.', 'A', '90']

The rule

split is adequate for self-written files. For any other CSV, use the csv module.

The csv module · rows as lists

csv.reader: each row arrives split

The reader wraps the open file and yields rows as lists. next(reader) removes the header row before the loop.

import csv with open("grades.csv") as f: reader = csv.reader(f) header = next(reader) # take the top row for row in reader: print(row) ['Ana', 'A', '88'] ['Ben', 'B', '74'] …
  • reader = csv.reader(f)wrap the open file: each row will come out as a list of strings
  • header = next(reader)take the first row (the column names) off the top
  • for row in reader:the remaining rows, one list per pass
The csv module · rows as dicts

DictReader: rows accessed by name

It uses the header row as keys, so each row is a dict — row["score"] instead of row[2]. This is the list-of-dicts shape from Part C, read directly from disk.

with open("grades.csv") as f: rows = list(csv.DictReader(f)) print(len(rows)) print(rows[0]) 5 {'name': 'Ana', 'section': 'A', 'score': '88'}

Values remain strings

'88', not 88. CSV has no types, so int(row["score"]) must be done explicitly.

  • list(csv.DictReader(f))read every row as a dict (header names as keys) and collect them in a list
  • len(rows) → 5five data rows; the header is not counted
  • rows[0]the first row: a dict, so rows[0]["name"] is 'Ana'
Exercise · 3 min

Selecting rows by a column

DictReader gives each row as a dictionary, so a column is read by its name.

Tasks

  1. Predict how many students scored 80 or more.
  2. Select ▶ Run / Edit and run the code.
  3. Change 80 to 90. Who is left?

Result on the lecture laptop (select to reveal)

3: ['Ana', 'Carla', 'Diego']. With 90, only ['Carla'].

with open("grades.csv") as f: rows = list(csv.DictReader(f)) high = [r["name"] for r in rows if int(r["score"]) >= 80] print(len(high), high)
The csv module · writing

Writing results as CSV

csv.writer handles the commas and quoting automatically: one writerow per line, header first. w.writerow([...]) takes a list and writes it as one comma-separated line. The grey block shows the resulting file contents.

with open("summary.csv", "w", newline="") as f: w = csv.writer(f) w.writerow(["section", "mean_score"]) w.writerow(["A", 82.0]) w.writerow(["B", 78.0]) print(open("summary.csv").read(), end="") section,mean_score A,82.0 B,78.0

The newline="" argument

Required when writing CSV; without it, Windows inserts blank lines between rows. It should always be included.

Review question

Question (select to reveal the answer)

After rows = list(csv.DictReader(f)), what is rows[0]["score"] + 2?

A · 90
B · '882'
C · A TypeError
D · '88 + 2'

C — TypeError: cannot add str and int.

CSV values are always strings: rows[0]["score"] is '88'. Conversion is required first: int(rows[0]["score"]) + 2 → 90. (B would be the answer for + "2" — string concatenation.)

Worked example

One program combining this week’s topics

Read a grades CSV → group scores by section → write a summary CSV. Containers, nesting and files in twelve lines.

Worked example · program

Read, group, average and write

DictReader loads rows; the grouping move collects scores per section; csv.writer saves the answer. All three patterns appear below.

  • rows = list(csv.DictReader(f))1 · read: every row as a dict
  • by_sec[sec].append(int(…))2 · group: each score, converted to a number, into its section’s list
  • for sec in sorted(by_sec):3 · write: the sections in order A, B (sorting a dict sorts its keys)
  • round(… , 1)the mean, rounded to 1 decimal place
import csv with open("grades.csv") as f: rows = list(csv.DictReader(f)) by_sec = {} for r in rows: sec = r["section"] if sec not in by_sec: by_sec[sec] = [] by_sec[sec].append(int(r["score"])) with open("summary.csv", "w", newline="") as f: w = csv.writer(f) w.writerow(["section", "mean_score"]) for sec in sorted(by_sec): w.writerow([sec, round(sum(by_sec[sec]) / len(by_sec[sec]), 1)])
Worked example · output

Five input rows, two output rows

This program was run when the deck was built. Input: 5 students, 2 sections. Output: one clean summary that another program (or Excel) can open.

print(open("grades.csv").read()) # the input print(open("summary.csv").read(), end="") # written by the program name,section,score Ana,A,88 Ben,B,74 Carla,A,91 Diego,B,82 Elena,A,67 section,mean_score A,82.0 B,78.0

Arithmetic check

Section A: (88 + 91 + 67) / 3 = 82.0. A pipeline should be spot-checked by hand at least once.

This week's lab

Lists, dicts and file totals

The lab covers slicing and sorting a list, unpack a tuple, count distinct values with a set, tally votes and group scores in a dictionary, write a small file and read it back, then read a CSV and average it per section — the full load-and-summarise loop. ~45 minutes.

How it works: replace each ____, press ▶ Run, then Check. Each part starts with a short reminder of the terms it uses.

Lab tasks

Indexing and slicing, .get() lookups, the tally pattern, and with open(...).

Optional extension

Re-run this week's worked example on a new CSV, change a score and observe the summary. Then add a count column per section.

Summary

Four containers, one loop pattern, reading and writing

Glossary

Week 3 terms

All new terms from this week, one line each. pandas (Weeks 6–7) is built on all of them.

Preparation for next week

Practice & reading

Next Week

Modular programming

Classes, errors and code organisation: keeping a program readable once it grows beyond a single notebook cell.

DS 208 · Programming for Data Science