7. Understanding Data
Opening
Big idea: A useful conclusion needs both suitable observations and a clear question.
Use a separate practice folder for the programs. Each example is self-contained unless its section says otherwise.
- Distinguish data, information, structure and measurement types.
- Plan collection, storage and processing with quality and privacy in mind.
- Read a CSV row from text to fields to numbers without losing rows.
- Compute and interpret central tendency and spread.
Read the rule, trace the worked example, and try the quick check before reading its answers. When a result surprises you, change one input and explain the difference.
This is an original lesson following the listed syllabus topics. Examples, datasets, questions and diagrams were created for this edition.
The previous chapter arranged records in order and found single entries fast. This chapter asks a different question: what does a whole collection say? Searching returns one record. Understanding data summarises many.
The chapter builds in stages. First the vocabulary: data, records, fields and metadata.
Then collection: what to record and whom to observe. Then storage: how to keep tables readable months later.
Then processing: turning text rows into numbers safely. Last, summaries: centre and spread.
Study by tracing. Cover each expected output and predict it first.
When a prediction fails, find the first line where your trace diverged. That line holds the lesson.
Short sentences carry one idea each. Read slowly rather than rereading later.
Two running datasets thread through every section. A class marks table holds five rows with maths and science marks; one science cell is empty.
A weather log holds five days with noon temperature and rain; one rain cell holds a dash. Watch how each stage treats the same gaps.
Expect small gaps everywhere. An absent student leaves an empty cell.
A faulty sensor leaves a dash. Later sections count such gaps openly, exclude them from totals, and divide only by observed rows.
Nothing is hidden and nothing is invented.
By the end, the marks table yields a class average with its missing row declared. The weather log yields a weekly centre with its spread. Both answers state their limits, which is what makes them trustworthy.
Trace tables and diagrams carry much of the teaching. A trace table shows one step per row. A diagram shows the shape of a process. Read each figure before reading on, and state its conclusion in your own words.
Complete Python examples have Copy code and an external run link. First predict the output. Run the example, then change one input and explain what changed. The output box shows the expected result; it is not another program.
7.1 INTRODUCTION TO DATA
A column containing numbers does not explain itself. A value might be a duration, an identifier or a category code. You need its meaning before you can decide which calculations make sense.
Data are the recorded observations. Information is what you learn when you interpret those observations in context. The same records may answer one question well and another badly.
- Name what each field describes.
- Record its unit or permitted categories.
- Ask a question that the collected fields can actually answer.
A teacher copies a marks table, but the numbers alone do not explain the class.
Data are recorded observations, measurements or symbols. Information is data interpreted in context to answer a question.
A column of numbers without units or a collection rule is difficult to interpret even when every number is copied correctly.
A record is one observed row. A field is one named column. Metadata describes the fields.
Read the table. Each row is one record: all the facts about one student. Each column is one field: one kind of fact across every student. The header row names the fields. Without it, nobody knows which column is which.
| id | maths | science |
|---|---|---|
| s1 | 70 | 81 |
| s2 | 80 | 79 |
| s3 | 70 | |
| s4 | 90 | 88 |
| s5 | 80 | 83 |
Read the table. Five records, three fields. The empty science cell for s3 is itself information: that mark is missing, not zero. A reader who guesses zero will compute a wrong average later.
A useful dataset includes metadata: descriptions such as field meanings, units, collection dates and permitted values. Metadata for this table would state the subject of each mark, the maximum possible mark, the test date, and that an empty cell means absent.
Keep metadata with the data, not in a separate message that can get lost.
Metadata for the marks table would list each field, its unit and its missing code. Maths and science are marks out of 100.
An empty cell means the student was absent. The test date and the class section complete the record.
Five lines of metadata protect five columns of data.
An identifier may contain digits but still be a label rather than a quantity; adding two identifiers usually has no useful meaning. The ids s1 to s5 order the rows.
Their digits do not measure anything. No total of identifiers answers a real question.
Read the table. Each row names a data shape and pairs it with this chapter.
Structured data has the marks-table shape: fixed rows and fields. Semi-structured data carries labelled fields with flexible shape, such as weather reports in JSON.
Unstructured data has no fixed schema, such as a photo of the whiteboard.
| Distinction | Examples |
|---|---|
| Structured | Rows with defined fields, such as duration and activity category. |
| Semi-structured | Records with labelled fields but flexible structure, such as JSON documents. |
| Unstructured | Free text, images or recordings without a fixed row-and-column schema. |
| Qualitative | Categories or descriptions, such as device type. |
| Quantitative | Numerical measurements or counts, such as elapsed seconds. |
Read the table above. The first three rows describe shape: how rigid the container is.
The last two rows describe content: categories versus quantities. One dataset can sit in two rows at once: the marks table is structured and its marks are quantitative.
Quantitative data can be discrete, such as a file count, or continuous in the model, such as duration. A stored rounded measurement remains a measurement even though the computer records finitely many possible values.
Temperature 31.5 is one of finitely many stored values, yet it still measures a continuous quantity.
Units belong in metadata, not in memory. One duration column in minutes beside another in seconds will silently corrupt any combined average.
Write the unit beside every field name before recording starts. A later reader cannot recover a unit nobody wrote down.
Qualitative data answers which-kind questions. How many students chose each activity is a count of categories, not a measurement.
The mode later fits such fields. Means do not, because category codes cannot be added meaningfully.
Classify three tracker fields: file count, download seconds and screen label.
Goal. Label each field as discrete, continuous or categorical.
Approach. Ask whether values count wholes, measure amounts or name kinds.
Trace. A file count grows by whole files only. Seconds measure time on a scale. A screen label names the current screen; its codes never add up.
Result. Discrete count, continuous measurement and qualitative category.
Result: File count is discrete, seconds are continuous, and the label is categorical.
Data become information only with context: units, rules and a question. Metadata is that context written down.
A file has identifier 104 and size 104 kilobytes. Are these the same kind of field?
Goal. Decide whether the shared digits make the two fields the same kind.
Approach. Ask what each field means and which operations make sense on it.
Trace. The identifier names a record; adding identifiers answers nothing. The size measures a quantity with a stated unit, and totals of sizes are useful.
Result. Their digits happen to match, but their meanings and valid operations differ.
Result: No. Their digits happen to match, but their meanings and valid operations differ.
Classify each field of the marks table as identifier, category or measurement.
Goal. Label the id, maths and science fields.
Approach. Ask for each field whether its values name, group or measure.
Trace. The id names a row and cannot be averaged. Both mark columns measure performance in marks, so totals and averages make sense.
Result. Identifier plus two measurements; no category field is present.
Result: The id is an identifier. Both mark columns are quantitative measurements.
7.2 DATA COLLECTION
If you ask only people who finished a task, you learn about finishers. You do not automatically learn why other people left. A collection method decides which experiences become visible.
A sample is a selected part of the population you care about. Choosing that sample carefully matters as much as collecting many responses. Missing observations also need a documented meaning.
- Define the group or events you want to understand.
- Choose a collection method that can reach that group.
- Record what was excluded, missing or not yet known instead of silently filling the gaps.
A weather club plans a month of noon readings before buying any instrument.
Collection design determines which questions the data can fairly answer. Decisions made before recording starts cannot be repaired afterwards by clever analysis.
A clear question is cheaper than a second collection round.
Primary data are collected directly for the task, such as measuring session lengths. Secondary data were collected earlier or by another source, such as a published dataset.
Secondary data still need checks for definitions, coverage, permission and suitability.
Last year weather file may define noon differently, skip rainy days, or use another instrument. Reusing it without those checks imports its blind spots into the new conclusion.
Permission matters too: some datasets forbid the planned reuse.
A population is the group of interest; a sample is the subset observed. A convenience sample is easy to obtain but may represent only the people or events easiest to reach.
Collecting more biased observations does not automatically remove that bias.
Five school days of noon temperature describe those five days only. They cannot prove a claim about the whole season.
The population is every day of interest; the sample is the days actually recorded. Name both before collecting.
- State the question and the population.
- Define fields, units and allowed values before collecting.
- Choose a sampling or observation method that matches the question.
- Test the collection form on a small pilot.
- Record missingness and unusual conditions.
- Collect only necessary personal data and explain its permitted use.
Read the list. Each step prevents one classic failure.
The question fixes the population. Defined fields stop mid-project changes.
The method matches the question instead of convenience. The pilot catches form errors early.
Missingness records protect honesty. Privacy limits protect people.
Read the diagram. The first two boxes fix purpose and vocabulary.
The middle two choose whom to observe and test the plan small. The last two admit gaps and protect privacy.
Skipping any box borrows trouble for the analysis stage.
A pilot is a small trial run of the full procedure. Two days of weather recording reveal a confusing field, a dead battery pattern, or a form with no space for unusual conditions.
Fixing the form after two days costs little. Fixing it after two hundred rows costs the whole dataset.
Read the table. Each pilot finding earns one concrete fix before full recording starts.
Unclear names get units attached. Missing entries get an explicit code.
Timing doubts get a recorded observation time. The pilot pays for itself in avoided rework.
| Pilot finding | Fix before full collection |
|---|---|
| Field "temp" is unclear. | Rename it to noon_temp_c with the unit. |
| Two rows lack rain entries. | Add an explicit missing code plus a notes field. |
| Evening entry typed next morning. | Record the observation time, not the typing time. |
Match the method to the question. Counting every late arrival for a week suits a small class.
Sampling a few corridors suits a large school. A census observes every member; a sample observes some.
Choose a census when the group is small and reachable, and a sample when it is large or spread out.
A teacher studies late arrivals in her class of 30. A city office studies arrivals across 200,000 commuters. Who can use a census?
Goal. Choose census or sample for each case.
Approach. Ask whether every member can realistically be observed.
Trace. Thirty students can each be recorded daily for a week. Two hundred thousand commuters cannot all be followed, so a sample of routes or days must stand in.
Result. The class takes a census; the city samples and states its method.
Result: The class observes all 30; the city samples and documents how.
A survey about all users is shown only to users who completed a long tutorial. What limitation should the report state?
Goal. Name the bias and the sentence the report must carry.
Approach. Ask who could not respond and how they might differ.
Trace. Users who left early cannot respond. Their experience may differ from that of successful completers.
Result. The sample excludes an important group, so conclusions about all users need caution.
Result: The sample excludes an important group, so conclusions about all users need caution.
A club reuses last year weather file to pick this year sports day. What must it check first?
Goal. List the reuse checks before trusting the file.
Approach. Compare definitions, coverage, instruments and permission with the new task.
Trace. Noon may be defined differently, rainy days may be missing, and the file may forbid this reuse. Each gap changes the answer.
Result. Confirm matching definitions and coverage, then reuse; otherwise collect fresh readings.
Result: Check definitions, coverage and permission before reusing any secondary file.
Distinguish a zero observation from a missing observation. A sensor reporting no reading has not necessarily measured a zero value.
Preserve the original record and document any correction. Rain 0 means a dry day was observed.
A dash means nobody observed that day.
A large sample cannot fix a systematically excluded group. More rows of the same biased kind only repeat the bias confidently.
7.3 DATA STORAGE
A saved file is not useful if a later reader cannot identify its fields or know which version is current. Storage planning includes meaning, identity, access and recovery, not just the choice of a folder.
Think about the next person opening the dataset. They should know the format, units and permitted values without guessing. They should also know how to recover an earlier usable version if the active copy is damaged.
- Keep a clear field description beside the stored records.
- Choose stable identifiers and a controlled editing process.
- Test that the recovery copy can actually be restored.
A shop keeps its inventory in three notebooks, and nobody knows which one is current.
A storage plan should make the data recoverable, understandable and appropriately accessible. Three notebooks with the same title fail all three tests at once. One controlled source of truth replaces them.
A file is a storage container, while a format explains its contents. CSV works well for simple tables but needs documented separators, quoting and encoding.
JSON supports nested labelled values. A database provides managed queries and integrity rules for related records.
A CSV file stores a table as text lines. Its header names the fields. Its delimiter separates them.
Read the code. The first line is the header: three field names. Each later line is one record. The comma is the delimiter that splits fields. No comma may hide inside a field unless quoting rules are documented.
item,price,stock
pen,20,150
pencil,10,200
notebook,45,80Read the code. Three records follow the header.
Each row carries the same three fields in the same order. A reader can state the price of a pencil without guessing: second row, second field.
That certainty is the whole point of a header.
Read the table. CSV fits flat tables with free tools.
JSON fits nested records such as an order with several lines. A database fits related tables with rules the machine enforces.
The shape of the data selects the format, not fashion.
| Format | Fits best | Watch out for |
|---|---|---|
| CSV | One flat table, simple tools. | Document delimiter, quoting and encoding. |
| JSON | Nested labelled values. | Larger files; schema stays a convention. |
| Database | Related tables with integrity rules. | Needs setup and managed access. |
A field containing a comma needs quoting rules. A location written as hall, room 4 would split into two fields without quotes.
Document whether fields may be quoted and how a quote inside a field is written. Test one such row before trusting the whole file.
JSON nests values inside labelled braces. One record can hold its own list.
{
"order": 501,
"customer": "s12",
"lines": [
{"item": "pen", "qty": 4},
{"item": "notebook", "qty": 1}
]
}Read the code. The order number and customer id sit at the top level.
The lines list holds two entries, each with its own item and quantity. A flat CSV would need awkward extra columns or a second table for the same order.
Nesting matches the shape of the thing stored.
A database adds guarantees that files alone cannot give. Two tables can share one customer list instead of copying it.
Types and required fields are enforced at write time. Queries join related rows without manual copying.
Small one-table tasks may not need this machinery.
| Concern | Practical design choice |
|---|---|
| Meaning | Keep field definitions and units with the dataset. |
| Identity | Give each record a stable identifier. |
| Access | Limit reading and editing to appropriate users. |
| Recovery | Keep tested backups and a clear restoration process. |
| Consistency | Use explicit types and validation rules. |
| Longevity | Choose documented formats and record software assumptions. |
Read the table. Each row answers one worry.
Meaning keeps future readers honest. Identity survives sorting.
Access limits damage. Recovery survives accidents.
Consistency catches bad rows early. Longevity survives software changes.
Local storage, removable devices and remote services have different availability and access risks. Synchronisation is not necessarily a backup: a deletion can synchronise too.
A backup needs a version or recovery point that survives the relevant failure.
Test every backup by restoring it. An untested copy may be incomplete or unreadable exactly when it is needed. Schedule the test and record its result beside the dataset.
A team emails several files called final.csv. Why is that a storage problem?
Goal. Explain what the shared name hides.
Approach. Ask which version is authoritative and which edits each copy holds.
Trace. The name does not reveal which version is authoritative or which edits are included. Two editors produce two different finals.
Result. Merging becomes guesswork and good edits can be lost.
Result: Use a documented versioning process and one controlled source of truth.
An order holds a customer, a date and three line items. Should it live in one CSV row?
Goal. Choose between CSV and JSON for a nested order.
Approach. Ask whether the shape is flat or nested.
Trace. One row cannot hold three line items without awkward extra columns. JSON nests the lines under one order naturally.
Result. JSON fits here; CSV fits flat tables.
Result: Use JSON for the nested order and CSV for flat tables.
Store as little identifying information as the task needs. Restrict access to raw records when summaries are sufficient. Deleting a visible copy does not prove that every backup or shared copy has also been deleted.
Access levels make this concrete. A cashier needs stock counts but not supplier costs.
A manager needs both. One shared login cannot enforce that split; named accounts with stated permissions can.
Review the permission list whenever roles change.
7.4 DATA PROCESSING
Processing is a chain of decisions. You may check a field, reject a malformed record, convert units and calculate a summary. Each step can change what the final answer means.
Keep raw input separate from the cleaned result. Then another person can inspect what was changed and repeat the work. A surprising value should lead to investigation, not automatic deletion.
- Validate the structure and meaning of incoming records.
- Apply a stated correction or rejection policy.
- Summarise the accepted data and report the omissions alongside the result.
The marks file is ready, but the average still needs careful work.
Processing turns collected records into a reproducible answer through explicit transformations. Every step is written down so another person can repeat it. Reproducibility separates analysis from guesswork.
Validation checks whether a value meets a rule. Cleaning addresses errors or inconsistencies using a documented policy.
Transformation changes representation or derives new fields. Aggregation combines records into summaries.
These are different steps, even when one program performs them together.
Read each term against the marks table. Validation asks whether a mark lies within range.
Cleaning decides what to do with the empty science cell. Transformation might derive a pass column from each mark.
Aggregation computes the class average from all accepted rows.
Read the diagram. Text enters at the top and values leave at the bottom.
Stripping cleans invisible spaces. Splitting finds the fields.
Conversion changes text to numbers. Validation and aggregation finish the job.
Skipping a box means the next box receives the wrong kind of thing.
A CSV row is text until the program interprets it. The split method cuts a line at each comma and returns the list of fields.
Watch the count: three fields per row here. A row with two fields signals a structural problem, not a small number.
Write down what this program should print before you read the expected output.
rows = ["s1,70,81", "s2,80,79", "s3,70,", "s4,90,88", "s5,80,83"]
for row in rows:
parts = row.split(",")
print(len(parts), parts[0], parts[1])Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores five text rows, exactly as a file would supply them. No numbers exist yet.
- Line 2 takes the rows one at a time. Line 3 cuts the current row at each comma.
- Line 4 prints three things: the field count, the id and the maths text. Every row reports 3 fields.
- The third row prints an empty-looking tail later; its maths text is still present and correct.
3 s1 70
3 s2 80
3 s3 70
3 s4 90
3 s5 80Change the printed index from 1 to 2. Predict what the third row prints.
Real files add untidy spaces. The strip method removes leading and trailing whitespace. Apply it before comparing or converting fields. A space is invisible on screen but decisive in code.
Try to predict the printed result first. The trace below explains every line.
for value in [" 18 ", "72 ", " 90"]:
cleaned = value.strip()
print(repr(cleaned), int(cleaned))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 supplies three texts with extra spaces, like hastily typed cells.
- Line 2 strips each value. Repr shows the quotes so invisible spaces would be visible.
- Line 3 converts the cleaned text to a number. Stripping first keeps later comparisons exact.
'18' 18
'72' 72
'90' 90Add " 7" to the list. Predict its printed line.
Conversion changes text into a number, and it can fail honestly. The int function accepts digit text and rejects everything else with an error.
A program should catch that error and record the position, not invent a value.
Read the table. Text plus a number is an error, not arithmetic. Two texts join; two numbers add. Conversion decides which world each value lives in. The rule is strict so mistakes surface loudly.
| Expression | Result |
|---|---|
| 82 + 1 | 83 |
| "82" + "1" | "821" |
| int("82") + 1 | 83 |
| int("") | Error: record the position. |
Read the table. The first row adds numbers.
The second joins texts, which surprises beginners. The third converts first, then adds.
The last row fails, and the failure is the correct behaviour: silence would corrupt the total.
The wrong delimiter silently keeps a row whole. Splitting a comma row at semicolons returns one long field instead of three. The count check from the first program would catch it at once.
Before running the program, say the output in your own words.
row = "s1,70,81"
print(row.split(";"))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores one comma-separated row as text.
- Line 2 splits at semicolons, which never occur. The result is a list with one long field.
- A later conversion of that field would fail. The field-count check is the early alarm.
['s1,70,81']Split the same row at commas. Predict the printed list.
Check missing values, repeated records, inconsistent units and impossible ranges. A repeated measurement is not necessarily an accidental duplicate; use record identity and collection context to decide.
Do not delete a surprising value merely because it makes the result inconvenient.
Predict the output before running this complete example.
raw = ["12", " 18 ", "", "bad", "9"]
accepted, rejected = [], []
for position, value in enumerate(raw):
try:
minutes = int(value)
if minutes < 0:
raise ValueError("negative duration")
except ValueError:
rejected.append(position)
else:
accepted.append(minutes)
print(sum(accepted))
print(rejected)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Each record is processed with its original position.
- Conversion and the nonnegative rule both need to succeed before the value is accepted.
- The failure path records the position rather than inventing a zero.
- The final total uses only accepted values, while the rejected list records the omissions.
39
[2, 3]Add a negative numeric string and explain why parsing alone is not enough validation.
Line 1 stores five texts. Lines 2 to 11 walk them with their positions. Conversion and the non-negative rule both need to succeed before a value is accepted.
The value 12 converts cleanly. The text " 18 " carries spaces, yet int accepts it; stripping would still be tidier.
The empty string fails conversion. The word bad fails too.
The value 9 converts. Accepted values are 12, 18 and 9.
This program reports rejected positions rather than silently treating them as zero. A real report should also state how many records were rejected and whether those omissions could change the conclusion.
Positions 2 and 3 wait aside with their reasons.
Read the diagram. The raw copy is frozen first. Each rule is checked openly. Bad rows are quarantined, never silently repaired. Only accepted rows enter the summary, and the report names what was left out.
The missing science cell needs the same honesty. An empty field means absent, so the program counts it separately and averages only the four present marks. Dividing by five would punish the class for a missing paper.
Write down what this program should print before you read the expected output.
rows = ["s1,70,81", "s2,80,79", "s3,70,", "s4,90,88", "s5,80,83"]
total, count, missing = 0, 0, 0
for row in rows:
science = row.split(",")[2]
if science == "":
missing += 1
else:
total += int(science)
count += 1
print(total)
print(count)
print(missing)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 restores the five marks rows with one empty science cell.
- Line 2 starts three counters: total, accepted count and missing count.
- Lines 3 to 9 handle each row. An empty field raises the missing counter only. A present field is converted and added.
- The prints show total 331, accepted count 4 and missing 1. The average must divide by four, not five.
331
4
1Fill the empty cell with 76. Predict all three printed numbers.
The maths column has no gaps, so its average is straightforward. Add all five marks for 390, count five rows, and divide. Each number below comes from the kit, not from mental arithmetic.
Try to predict the printed result first. The trace below explains every line.
rows = ["s1,70,81", "s2,80,79", "s3,70,", "s4,90,88", "s5,80,83"]
total = 0
count = 0
for row in rows:
maths = int(row.split(",")[1])
total += maths
count += 1
print(total)
print(count)
print(total / count)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 restores the five rows. Lines 2 and 3 start the counters at zero.
- Lines 4 to 7 take the second field of each row, convert it and accumulate. The third field is never touched.
- The prints show total 390 over 5 rows. The division gives 78.0, the class mean in maths.
390
5
78.0Add a sixth row "s6,85,80". Predict all three printed numbers.
Cleaning must never invent data. Quarantine, count and report every rejected row.
Transformation derives new fields from old ones. A pass column applies one rule to every maths mark: 75 or above passes.
The program below writes the derived field beside each id. The raw marks stay untouched; the new column is a separate, documented result.
Before running the program, say the output in your own words.
rows = ["s1,70,81", "s2,80,79", "s3,70,", "s4,90,88", "s5,80,83"]
for row in rows:
parts = row.split(",")
result = "pass" if int(parts[1]) >= 75 else "fail"
print(parts[0], result)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 restores the five marks rows.
- Line 3 cuts each row into fields. Line 4 converts the maths text and applies the 75-mark rule.
- Line 5 prints the id with its derived result. Two rows pass the rule and three do not. The empty science cell never interferes, because only the maths field is read.
s1 fail
s2 pass
s3 fail
s4 pass
s5 passRaise the bar to 80. Predict which rows change their result.
A row reads "d3,31,-" for rain. Should the dash become 0 before averaging?
Goal. Decide how the missing rain reading enters the average.
Approach. Ask whether a dash observes dry weather or observes nothing.
Trace. The dash means nobody observed that day, while 0 would claim a dry day. Four readings total 8, so the mean divides by four.
Result. Keep the dash out of the total and report one missing day.
Result: Exclude the dash and average the four observed readings.
The science column has four values but five students. Which count divides the total?
Goal. Choose the divisor for the science mean.
Approach. Count only rows that actually supply a science mark.
Trace. Four marks total 331. The empty cell contributes no mark and no row to the divisor. 331 divided by 4 is 82.75.
Result. Divide by the available count, and state the missing row beside the answer.
Result: Divide 331 by 4 to get 82.75.
7.5 STATISTICAL TECHNIQUES FOR DATA PROCESSING
A single average cannot describe every feature of a dataset. Two groups can have similar central values while one group is tightly clustered and the other is widely spread.
Mean, median and mode answer different “typical value” questions. Range and standard deviation describe spread in different ways. Choose the measure from the meaning of the data rather than choosing whichever calculation is easiest.
- Inspect the observations and their unit.
- Choose and calculate a suitable centre.
- Describe spread and investigate any extreme observations before interpreting the summary.
Two classes both average 78, but one is steady and the other swings widely.
The arithmetic mean is the sum divided by the observation count. Add every value first. Count the values next. Divide, and keep the steps visible. Hidden mental arithmetic is where wrong averages are born.
The mean balances every value. The median marks the middle position. The mode names the most frequent value.
Summarise session durations 3, 5, 5, 7 in minutes.
The sum is 20. Divide by the count for the mean. The sorted middle pair consists of equal values. Count repetitions for the mode.
Result: Mean = 5; median = 5; mode = 5.
Read the worked example. Four durations sum to 20. Four observations give mean 5. Sorted, the middle pair is 5 and 5, so the median is 5. The value 5 occurs twice, more than any other, so the mode is 5.
With an even count, add the central pair and divide by two. Here both central values are 5, so the median is 5 without controversy. With an odd count, the single middle value after sorting is the median.
The median is the middle value after sorting; with an even count, add the central pair and divide by two. The mode is a most frequent value; several values can tie for highest frequency.
The maths marks show a genuine tie. Sorted, they read 70, 70, 80, 80, 90. The middle is 80, so the median is 80. Both 70 and 80 occur twice, so both share the mode. A tie is an answer, not a failure.
Write down what this program should print before you read the expected output.
import statistics
maths = [70, 80, 70, 90, 80]
print(statistics.mean(maths))
print(statistics.median(maths))
print(statistics.multimode(maths))
print(statistics.pvariance(maths))Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- Line 1 loads the statistics helpers. Line 2 stores the five maths marks with each value repeated as in class.
- Line 3 prints the mean: total 390 divided by 5 gives 78.
- Line 4 prints the median of the sorted marks: the middle value 80.
- Line 5 prints both tied modes as a list. Line 6 prints the population variance 56, explained in the next part.
78
80
[70, 80]
56Change the last mark from 80 to 100. Predict the mean and the mode list.
Read the expected output. Four lines, four summaries of the same column. The list on the third line is the honest shape for modes: one list that can hold one value, two values, or every value when nothing repeats.
| Sorted maths | Position | Note |
|---|---|---|
| 70 | 1 | Lower copy of the tied mode. |
| 70 | 2 | Upper copy of the tied mode. |
| 80 | 3 | Middle: the median. |
| 80 | 4 | Second copy of the tied mode. |
| 90 | 5 | Highest mark. |
Read the table. Sorting exposes the structure that arrival order hides. The median sits at position 3. The tied modes occupy two positions each. No step here needs a calculator, only careful ordering.
The range is maximum minus minimum. It uses only the endpoints.
Variance averages squared distances from the mean under a stated convention. Standard deviation is its square root and therefore has the original measurement unit.
A centre without a spread can mislead. Report both together.
The noon temperatures show a calm week. Values 30, 32, 31, 34, 33 total 160, so the mean is 32. Sorted, the middle is 32. Maximum minus minimum is 4. Every value occurs once, so there is no useful mode.
Try to predict the printed result first. The trace below explains every line.
import statistics
temps = [30, 32, 31, 34, 33]
print(statistics.mean(temps))
print(statistics.median(temps))
print(max(temps) - min(temps))Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- Line 1 loads the statistics helpers. Line 2 stores the five noon temperatures.
- Line 3 prints the mean 32: total 160 over 5 days.
- Line 4 prints the median of the sorted week: the middle day reads 32.
- Line 5 subtracts the coolest day from the warmest: range 4.
32
32
4Change the last temperature from 33 to 39. Predict all three printed lines.
Squaring keeps below-mean and above-mean distances from cancelling. Each deviation is measured, squared, and then averaged. The square root at the end restores the original unit: minutes, marks or degrees.
| Value | Deviation from mean | Squared deviation |
|---|---|---|
| 3 | -2 | 4 |
| 5 | 0 | 0 |
| 5 | 0 | 0 |
| 7 | 2 | 4 |
Add the squared deviations and divide by the observation count for population variance: 8 divided by 4 gives 2. Taking its square root returns the population standard deviation.
For these observations, population variance is 2, range is 4, and population standard deviation is about 1.414214. Here “population” means the listed observations themselves are the full collection being summarised.
A sample-variance estimate for a larger population usually divides by one fewer than the count instead; do not mix the two formulas.
Predict the output before running this complete example.
import statistics
values = [3, 5, 5, 7]
print(statistics.mean(values))
print(statistics.median(values))
print(statistics.multimode(values))
print(statistics.pvariance(values))Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- The same small dataset is passed to each summary function.
- Mean uses every numeric value; median uses ordered middle positions.
- Multimode returns a list because several values may tie for highest frequency.
- Pvariance uses the population convention for the complete supplied collection.
5
5.0
[5]
2Replace one observation with a much larger value and compare the effect on the mean and median.
Line 2 stores the same four durations studied above. Lines 3 to 6 ask four summary questions. Each printed line answers one question about the identical data.
Read the output. Mean 5 balances the values. Median 5.0 marks the middle; the decimal point only shows a float result. Mode [5] arrives as a one-item list. Population variance 2.0 spreads in squared minutes.
Four session durations in minutes are plotted at their observation positions, with a horizontal line showing their mean.
Read the figure. Four dots mark the observations in order: 3, 5, 5, 7.
The flat line at 5 is the mean. Dots above and below it show the variation the single number hides.
A summary without spread would claim these four identical weeks, which they are not.
Adding an observation of 30 changes the mean to 10, while the median remains 5. This illustrates sensitivity to an extreme value; it does not justify discarding that value without investigation.
Read the change plainly. The total becomes 50 over 5 observations, so the mean doubles to 10. The sorted list gains one high value at the end; the middle stays 5. One number moved, the other stood still.
Means and standard deviations require meaningful numeric measurements. For nominal categories, counts and a mode may be useful while an average category code is not.
Summaries can hide group differences, so inspect the observations and context too.
Two classes both average 78. Class A scored 76, 78 and 80. Class B scored 60, 78 and 96. Which class is steadier?
Goal. Compare the spread of two classes with equal means.
Approach. Total each class for the mean, then take maximum minus minimum for the range.
Trace. Both totals are 234, so both means are 78. Class A spans 4 marks; Class B spans 36.
Result. Equal centres hide very different spreads; the mean alone cannot tell the classes apart.
Result: Both average 78, but Class A ranges 4 while Class B ranges 36.
Read the table. The question selects the summary: counting questions take the mode, centre questions take mean or median, spread questions take range or deviation. The last row is a warning, not a summary.
| Question | Suitable summary |
|---|---|
| Which activity is most common? | Mode of the category field. |
| What is a typical mark? | Mean or median of the marks. |
| How widely do marks vary? | Range, variance or standard deviation. |
| Is variance 56 large? | Only against context, never alone. |
Read the diagram. The question comes first, always.
Categories are counted. Numeric centres are balanced or ordered.
Spread accompanies every centre. The variance row names its convention, because the divisor changes the value.
Centre tells where; spread tells how far. Never report one without the other.
Predict the mean and median after a 30 joins 3, 5, 5 and 7.
Goal. State both summaries without running code.
Approach. Retotal for the mean; resort positions for the median.
Trace. The total becomes 50 over 5, so the mean is 10. The sorted middle stays 5.
Result. The mean doubles while the median stands still.
Result: Mean 10, median 5. Sensitivity is a fact, not a fault.
Summary
Use these points to test what you can explain without looking back.
- Data become useful information through context and a question.
- A record is one row and a field is one column; metadata define both.
- CSV stores flat tables as text with a header and a documented delimiter.
- Sampling and collection bias matter even for large datasets.
- Separate raw data, cleaning rules and derived results.
- Convert text to numbers openly; quarantine and count every rejected row.
- Choose central tendency and spread measures appropriate to the measurement type.
- State the variance convention and investigate extreme values rather than hiding them.
Exercise
Work independently. For a program, predict the result before running it. Explain your reasoning as well as giving an answer.
7.1 Explain why a postal-style code is usually categorical even if it contains only digits.
7.2 What is a risk of a voluntary survey about satisfaction?
7.3 A missing temperature is stored as zero. Why can the mean become misleading?
7.4 Give the mean and median of 3, 5, 5, 7.
7.5 Give its range and population variance.
7.6 Why is a mode useful for a device-category field?
7.7 Explain why a backup should be tested.
7.8 Why should a report include rejected-record counts?
7.9 Does a small standard deviation prove a measurement system is accurate?
7.10 Why can a median be more resistant than a mean to one extreme observation?
7.11 Predict the output, then name the contract this loop answers.
Before running the program, say the output in your own words.
rows = ["s1,70,81", "s2,80,79", "s3,70,", "s4,90,88", "s5,80,83"]
for row in rows:
parts = row.split(",")
print(len(parts), parts[0], parts[1])Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores five text rows exactly as a file supplies them.
- Each row is cut at commas into three fields.
- Every print shows the count 3 with the id and maths text.
3 s1 70
3 s2 80
3 s3 70
3 s4 90
3 s5 80Print the third field instead of the second. Predict the empty-looking line.
7.12 Trace the missing-value counter on the science column.
| Row | Science field | Action |
|---|---|---|
| s1 | 81 | Add to total. |
| s2 | 79 | Add to total. |
| s3 | (empty) | Count as missing. |
| s4 | 88 | Add to total. |
| s5 | 83 | Add to total. |
7.13 This import splits every row at semicolons. Name the fault and give the repair.
for row in rows:
parts = row.split(";")
print(parts[1])7.14 Write the maths-average program and show its three printed lines.
Write down what this program should print before you read the expected output.
rows = ["s1,70,81", "s2,80,79", "s3,70,", "s4,90,88", "s5,80,83"]
total = 0
count = 0
for row in rows:
maths = int(row.split(",")[1])
total += maths
count += 1
print(total)
print(count)
print(total / count)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The second field of each row is converted and accumulated.
- Five rows give total 390 and count 5.
- The division prints the class mean 78.0.
390
5
78.0Add a sixth row with maths 85. Predict the new total and mean.
7.15 Trace the mids of the median for five sorted temperatures.
| Step | Sorted position | Value |
|---|---|---|
| 1 | 1 | 30 |
| 2 | 2 | 31 |
| 3 | 3 | 32 (median) |
| 4 | 4 | 33 |
| 5 | 5 | 34 |
7.16 Explain the tied modes of the maths marks without using the word average.
Try to predict the printed result first. The trace below explains every line.
import statistics
maths = [70, 80, 70, 90, 80]
print(statistics.mean(maths))
print(statistics.median(maths))
print(statistics.multimode(maths))
print(statistics.pvariance(maths))Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- The mean balances all five marks at 78.
- The sorted middle is 80.
- Both 70 and 80 occur twice, so the mode list holds two values.
78
80
[70, 80]
56Replace the final 80 with 81. Predict the new mode list.
7.17 This median shortcut prints 3 for [7, 3, 5]. Name the fault and give the repair.
values = [7, 3, 5]
print(values[len(values) // 2])7.18 Write the rain-average program and show its three printed lines.
Before running the program, say the output in your own words.
rows = ["d1,30,2", "d2,32,0", "d3,31,-", "d4,34,5", "d5,33,1"]
total, count = 0, 0
for row in rows:
rain = row.split(",")[2]
if rain != "-":
total += int(rain)
count += 1
print(total)
print(count)
print(total / count)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores five weather rows with one dash for missing rain.
- Lines 4 to 7 skip the dash and accumulate only observed readings.
- The prints show total 8 over 4 days, giving mean 2.0.
8
4
2.0Change the dash to 6. Predict the new total and mean.
Answers
7.1 It labels a category or location; numeric arithmetic on the code has no ordinary measurement meaning.
7.2 People who choose to respond may differ systematically from those who do not.
7.3 Zero becomes a real measurement in the calculation unless missingness is represented and handled separately.
7.4 Both are 5.
7.5 Range 4; population variance 2.
7.6 It identifies a most frequent category without treating arbitrary category labels as quantities.
7.7 An untested copy may be incomplete, inconsistent or impossible to restore when needed.
7.8 Readers need to assess data loss and possible bias in the accepted sample.
7.9 No. Values can be tightly clustered around a systematically wrong value.
7.10 It depends on ordered middle positions rather than the magnitude of every observation.
7.11 3 s1 70 and four matching lines. It answers the parsing contract: every row yields three fields.
7.12 Total 331, count 4, missing 1. The mean divides by 4, giving 82.75.
7.13 The delimiter is wrong, so each row stays one field and index 1 fails. Split at commas and check that every row yields three fields.
7.14 390, 5 and 78.0. The total accumulates converted marks; the count tracks rows.
7.15 Five values sort to 30, 31, 32, 33, 34. The middle position 3 holds 32.
7.16 [70, 80]. Each occurs twice, which is more often than any other mark.
7.17 The list is unsorted, so the middle position holds 3 instead of the median 5. Sort first, then take the middle: sorted values give 5.
7.18 8, 4 and 2.0. The dash contributes no reading and no day to the divisor.