When a learner can reproduce a familiar example but a small variation causes confusion, the problem is usually an incomplete model rather than a lack of effort. The fastest useful response is to expose the hidden state and test one boundary at a time.
Python itertools.groupby divides an iterable into consecutive runs whose adjacent items produce the same key. It does not perform database-style global grouping. Mastery means predicting where a run starts and ends, arranging data deliberately when global categories are wanted, consuming each shared group iterator at the correct time and choosing another tool when aggregation rather than run detection is the real job. This guide begins with that mechanism, then develops it through worked traces, deliberate mistakes, explained practice and transfer decisions.
The aim is independent reasoning. A learner should be able to predict behaviour, locate the earliest wrong assumption, use a safe diagnostic procedure and defend a design choice in a new project.
Punggol families can use the guide in short sessions around homework, CCAs and rest. The activities are proposed learning exercises, not claims about a physical branch, timetable, class size, fee, school relationship or guaranteed result.
Use disposable data and repositories, preserve backups, and check version-sensitive details against the official source. Current documentation settles a technical contract; observation and explanation turn that contract into usable knowledge.
Find your next learning step
Choose the route that matches the present difficulty. Use the complete index for a systematic course.
Build the model
Chapters 1-4 . Begin here, then continue after the learner can predict, verify and explain.
Use the core tools
Chapters 5-8 . Begin here, then continue after the learner can predict, verify and explain.
Handle boundaries
Chapters 9-12 . Begin here, then continue after the learner can predict, verify and explain.
Debug and verify
Chapters 13-16 . Begin here, then continue after the learner can predict, verify and explain.
Transfer with judgment
Chapters 17-20 . Begin here, then continue after the learner can predict, verify and explain.
Open the full chapter index . Jump to capstone practice . Use the How Studying Works hub . Read the official documentation
Complete chapter index
Chapters 1-4 . Build the model
Chapters 5-8 . Use the core tools
Chapters 9-12 . Handle boundaries
Chapters 13-16 . Debug and verify
Chapters 17-20 . Transfer with judgment
groupby starts a new group whenever the key value changes while reading the iterable from left to right. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is expecting equal keys separated by another key to merge into one group. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Write the key beside every item and draw a boundary only where adjacent keys differ.
For the Consecutive runs are the central model chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on expecting equal keys separated by another key to merge into one group. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
from itertools import groupby
data=['A','A','B','A']
[(k,list(g)) for k,g in groupby(data)]Explained result. The result has A, B and A groups because the final A begins a new consecutive run. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: homework log. Predict the rule using consecutive subject labels and minutes studied. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “groupby starts a new group whenever the key value changes while reading the iterable from left to right.” Apply this procedure: Write the key beside every item and draw a boundary only where adjacent keys differ. The expected mechanism is: The result has A, B and A groups because the final A begins a new consecutive run. For the homework log, add one near-miss that exposes expecting equal keys separated by another key to merge into one group. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: library shelf. Contrast the rule using books ordered by section code and title. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “groupby starts a new group whenever the key value changes while reading the iterable from left to right.” Apply this procedure: Write the key beside every item and draw a boundary only where adjacent keys differ. The expected mechanism is: The result has A, B and A groups because the final A begins a new consecutive run. For the library shelf, add one near-miss that exposes expecting equal keys separated by another key to merge into one group. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: CCA attendance. Stress-test the rule using adjacent present, late and absent states. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “groupby starts a new group whenever the key value changes while reading the iterable from left to right.” Apply this procedure: Write the key beside every item and draw a boundary only where adjacent keys differ. The expected mechanism is: The result has A, B and A groups because the final A begins a new consecutive run. For the CCA attendance, add one near-miss that exposes expecting equal keys separated by another key to merge into one group. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: science readings. Explain the rule using runs of sensor status after threshold classification. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “groupby starts a new group whenever the key value changes while reading the iterable from left to right.” Apply this procedure: Write the key beside every item and draw a boundary only where adjacent keys differ. The expected mechanism is: The result has A, B and A groups because the final A begins a new consecutive run. For the science readings, add one near-miss that exposes expecting equal keys separated by another key to merge into one group. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers expecting equal keys separated by another key to merge into one group.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Write the key beside every item and draw a boundary only where adjacent keys differ.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from Consecutive runs are the central model?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing expecting equal keys separated by another key to merge into one group be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny budget list with transactions sorted by category before summarising. Include one ordinary case, one boundary and one deliberate failure caused by expecting equal keys separated by another key to merge into one group. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: groupby starts a new group whenever the key value changes while reading the iterable from left to right. It shows a trace, not only a final value. The ordinary case should demonstrate “The result has A, B and A groups because the final A begins a new consecutive run.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Write the key beside every item and draw a boundary only where adjacent keys differ. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For Consecutive runs are the central model, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
Each item is transformed by key, and consecutive transformed values are compared to decide group boundaries. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is grouping by the original item after supplying a different key function. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Make a two-column item-to-key table before consuming the groups.
For the The key function defines equality chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on grouping by the original item after supplying a different key function. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
words=['ant','ape','book','boat']
[(k,list(g)) for k,g in groupby(words,key=len)]Explained result. The lengths form runs 3 then 4, so the words are grouped by adjacent length values. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: CCA attendance. Contrast the rule using adjacent present, late and absent states. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Each item is transformed by key, and consecutive transformed values are compared to decide group boundaries.” Apply this procedure: Make a two-column item-to-key table before consuming the groups. The expected mechanism is: The lengths form runs 3 then 4, so the words are grouped by adjacent length values. For the CCA attendance, add one near-miss that exposes grouping by the original item after supplying a different key function. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: science readings. Stress-test the rule using runs of sensor status after threshold classification. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Each item is transformed by key, and consecutive transformed values are compared to decide group boundaries.” Apply this procedure: Make a two-column item-to-key table before consuming the groups. The expected mechanism is: The lengths form runs 3 then 4, so the words are grouped by adjacent length values. For the science readings, add one near-miss that exposes grouping by the original item after supplying a different key function. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: revision tracker. Explain the rule using topic attempts ordered by date and confidence band. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Each item is transformed by key, and consecutive transformed values are compared to decide group boundaries.” Apply this procedure: Make a two-column item-to-key table before consuming the groups. The expected mechanism is: The lengths form runs 3 then 4, so the words are grouped by adjacent length values. For the revision tracker, add one near-miss that exposes grouping by the original item after supplying a different key function. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: budget list. Transfer the rule using transactions sorted by category before summarising. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Each item is transformed by key, and consecutive transformed values are compared to decide group boundaries.” Apply this procedure: Make a two-column item-to-key table before consuming the groups. The expected mechanism is: The lengths form runs 3 then 4, so the words are grouped by adjacent length values. For the budget list, add one near-miss that exposes grouping by the original item after supplying a different key function. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers grouping by the original item after supplying a different key function.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Make a two-column item-to-key table before consuming the groups.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from The key function defines equality?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing grouping by the original item after supplying a different key function be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny text analysis with consecutive words classified by length or initial. Include one ordinary case, one boundary and one deliberate failure caused by grouping by the original item after supplying a different key function. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Each item is transformed by key, and consecutive transformed values are compared to decide group boundaries. It shows a trace, not only a final value. The ordinary case should demonstrate “The lengths form runs 3 then 4, so the words are grouped by adjacent length values.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Make a two-column item-to-key table before consuming the groups. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For The key function defines equality, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
To collect every item of a category together, sort by the same key before groupby, accepting that sorting changes order and materialises finite input. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is sorting by one rule and grouping by another related-looking rule. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Name one key function, reuse it for sort and groupby, and record the lost original order.
For the Sorting creates global category runs chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on sorting by one rule and grouping by another related-looking rule. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
key=str.lower
data=sorted(['b','A','a','B'],key=key)
[(k,list(g)) for k,g in groupby(data,key)]Explained result. Sorting makes equal lower-case keys adjacent, producing one a group and one b group. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: revision tracker. Stress-test the rule using topic attempts ordered by date and confidence band. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “To collect every item of a category together, sort by the same key before groupby, accepting that sorting changes order and materialises finite input.” Apply this procedure: Name one key function, reuse it for sort and groupby, and record the lost original order. The expected mechanism is: Sorting makes equal lower-case keys adjacent, producing one a group and one b group. For the revision tracker, add one near-miss that exposes sorting by one rule and grouping by another related-looking rule. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: budget list. Explain the rule using transactions sorted by category before summarising. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “To collect every item of a category together, sort by the same key before groupby, accepting that sorting changes order and materialises finite input.” Apply this procedure: Name one key function, reuse it for sort and groupby, and record the lost original order. The expected mechanism is: Sorting makes equal lower-case keys adjacent, producing one a group and one b group. For the budget list, add one near-miss that exposes sorting by one rule and grouping by another related-looking rule. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: text analysis. Transfer the rule using consecutive words classified by length or initial. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “To collect every item of a category together, sort by the same key before groupby, accepting that sorting changes order and materialises finite input.” Apply this procedure: Name one key function, reuse it for sort and groupby, and record the lost original order. The expected mechanism is: Sorting makes equal lower-case keys adjacent, producing one a group and one b group. For the text analysis, add one near-miss that exposes sorting by one rule and grouping by another related-looking rule. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: debug stream. Predict the rule using a generator that prints whenever its next item is requested. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “To collect every item of a category together, sort by the same key before groupby, accepting that sorting changes order and materialises finite input.” Apply this procedure: Name one key function, reuse it for sort and groupby, and record the lost original order. The expected mechanism is: Sorting makes equal lower-case keys adjacent, producing one a group and one b group. For the debug stream, add one near-miss that exposes sorting by one rule and grouping by another related-looking rule. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers sorting by one rule and grouping by another related-looking rule.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Name one key function, reuse it for sort and groupby, and record the lost original order.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from Sorting creates global category runs?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing sorting by one rule and grouping by another related-looking rule be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny debug stream with a generator that prints whenever its next item is requested. Include one ordinary case, one boundary and one deliberate failure caused by sorting by one rule and grouping by another related-looking rule. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: To collect every item of a category together, sort by the same key before groupby, accepting that sorting changes order and materialises finite input. It shows a trace, not only a final value. The ordinary case should demonstrate “Sorting makes equal lower-case keys adjacent, producing one a group and one b group.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Name one key function, reuse it for sort and groupby, and record the lost original order. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For Sorting creates global category runs, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
The iterator reports runs and does not automatically calculate counts, sums or one bucket per distinct key. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is transferring database expectations to a streaming iterator. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. State whether the task is run detection, category bucketing or aggregation before choosing the tool.
For the groupby is not SQL GROUP BY chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on transferring database expectations to a streaming iterator. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
[(k,sum(1 for _ in g)) for k,g in groupby('AAABB')]Explained result. This counts adjacent runs; on AABAA it would report two separate A counts. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: text analysis. Explain the rule using consecutive words classified by length or initial. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “The iterator reports runs and does not automatically calculate counts, sums or one bucket per distinct key.” Apply this procedure: State whether the task is run detection, category bucketing or aggregation before choosing the tool. The expected mechanism is: This counts adjacent runs; on AABAA it would report two separate A counts. For the text analysis, add one near-miss that exposes transferring database expectations to a streaming iterator. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: debug stream. Transfer the rule using a generator that prints whenever its next item is requested. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “The iterator reports runs and does not automatically calculate counts, sums or one bucket per distinct key.” Apply this procedure: State whether the task is run detection, category bucketing or aggregation before choosing the tool. The expected mechanism is: This counts adjacent runs; on AABAA it would report two separate A counts. For the debug stream, add one near-miss that exposes transferring database expectations to a streaming iterator. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: homework log. Predict the rule using consecutive subject labels and minutes studied. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “The iterator reports runs and does not automatically calculate counts, sums or one bucket per distinct key.” Apply this procedure: State whether the task is run detection, category bucketing or aggregation before choosing the tool. The expected mechanism is: This counts adjacent runs; on AABAA it would report two separate A counts. For the homework log, add one near-miss that exposes transferring database expectations to a streaming iterator. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: library shelf. Contrast the rule using books ordered by section code and title. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “The iterator reports runs and does not automatically calculate counts, sums or one bucket per distinct key.” Apply this procedure: State whether the task is run detection, category bucketing or aggregation before choosing the tool. The expected mechanism is: This counts adjacent runs; on AABAA it would report two separate A counts. For the library shelf, add one near-miss that exposes transferring database expectations to a streaming iterator. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers transferring database expectations to a streaming iterator.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “State whether the task is run detection, category bucketing or aggregation before choosing the tool.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from groupby is not SQL GROUP BY?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing transferring database expectations to a streaming iterator be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny homework log with consecutive subject labels and minutes studied. Include one ordinary case, one boundary and one deliberate failure caused by transferring database expectations to a streaming iterator. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: The iterator reports runs and does not automatically calculate counts, sums or one bucket per distinct key. It shows a trace, not only a final value. The ordinary case should demonstrate “This counts adjacent runs; on AABAA it would report two separate A counts.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: State whether the task is run detection, category bucketing or aggregation before choosing the tool. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For groupby is not SQL GROUP BY, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
Each returned group iterator reads from the same underlying iterable, and advancing the outer groupby invalidates unconsumed items from earlier groups. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is saving group iterators and consuming them after the outer loop has moved on. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Consume or copy each group inside the loop before asking for the next key.
For the The group iterator shares the source chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on saving group iterators and consuming them after the outer loop has moved on. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
groups=[]
for k,g in groupby('AAABB'):
groups.append((k,list(g)))Explained result. Materialising list(g) immediately preserves the group values before the shared source advances. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: homework log. Transfer the rule using consecutive subject labels and minutes studied. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Each returned group iterator reads from the same underlying iterable, and advancing the outer groupby invalidates unconsumed items from earlier groups.” Apply this procedure: Consume or copy each group inside the loop before asking for the next key. The expected mechanism is: Materialising list(g) immediately preserves the group values before the shared source advances. For the homework log, add one near-miss that exposes saving group iterators and consuming them after the outer loop has moved on. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: library shelf. Predict the rule using books ordered by section code and title. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Each returned group iterator reads from the same underlying iterable, and advancing the outer groupby invalidates unconsumed items from earlier groups.” Apply this procedure: Consume or copy each group inside the loop before asking for the next key. The expected mechanism is: Materialising list(g) immediately preserves the group values before the shared source advances. For the library shelf, add one near-miss that exposes saving group iterators and consuming them after the outer loop has moved on. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: CCA attendance. Contrast the rule using adjacent present, late and absent states. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Each returned group iterator reads from the same underlying iterable, and advancing the outer groupby invalidates unconsumed items from earlier groups.” Apply this procedure: Consume or copy each group inside the loop before asking for the next key. The expected mechanism is: Materialising list(g) immediately preserves the group values before the shared source advances. For the CCA attendance, add one near-miss that exposes saving group iterators and consuming them after the outer loop has moved on. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: science readings. Stress-test the rule using runs of sensor status after threshold classification. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Each returned group iterator reads from the same underlying iterable, and advancing the outer groupby invalidates unconsumed items from earlier groups.” Apply this procedure: Consume or copy each group inside the loop before asking for the next key. The expected mechanism is: Materialising list(g) immediately preserves the group values before the shared source advances. For the science readings, add one near-miss that exposes saving group iterators and consuming them after the outer loop has moved on. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers saving group iterators and consuming them after the outer loop has moved on.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Consume or copy each group inside the loop before asking for the next key.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from The group iterator shares the source?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing saving group iterators and consuming them after the outer loop has moved on be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny library shelf with books ordered by section code and title. Include one ordinary case, one boundary and one deliberate failure caused by saving group iterators and consuming them after the outer loop has moved on. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Each returned group iterator reads from the same underlying iterable, and advancing the outer groupby invalidates unconsumed items from earlier groups. It shows a trace, not only a final value. The ordinary case should demonstrate “Materialising list(g) immediately preserves the group values before the shared source advances.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Consume or copy each group inside the loop before asking for the next key. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For The group iterator shares the source, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
groupby pulls input as needed and can process long or streaming data without building all groups at once. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is calling list on the entire groupby result and claiming the workflow remains streaming. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Measure when source items are requested and retain only the current group summary.
For the Lazy reading limits memory chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on calling list on the entire groupby result and claiming the workflow remains streaming. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
for key,group in groupby(stream,key=classify):
handle(key,group)Explained result. The loop can process one run at a time when handle consumes the group before continuing. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: CCA attendance. Predict the rule using adjacent present, late and absent states. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “groupby pulls input as needed and can process long or streaming data without building all groups at once.” Apply this procedure: Measure when source items are requested and retain only the current group summary. The expected mechanism is: The loop can process one run at a time when handle consumes the group before continuing. For the CCA attendance, add one near-miss that exposes calling list on the entire groupby result and claiming the workflow remains streaming. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: science readings. Contrast the rule using runs of sensor status after threshold classification. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “groupby pulls input as needed and can process long or streaming data without building all groups at once.” Apply this procedure: Measure when source items are requested and retain only the current group summary. The expected mechanism is: The loop can process one run at a time when handle consumes the group before continuing. For the science readings, add one near-miss that exposes calling list on the entire groupby result and claiming the workflow remains streaming. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: revision tracker. Stress-test the rule using topic attempts ordered by date and confidence band. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “groupby pulls input as needed and can process long or streaming data without building all groups at once.” Apply this procedure: Measure when source items are requested and retain only the current group summary. The expected mechanism is: The loop can process one run at a time when handle consumes the group before continuing. For the revision tracker, add one near-miss that exposes calling list on the entire groupby result and claiming the workflow remains streaming. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: budget list. Explain the rule using transactions sorted by category before summarising. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “groupby pulls input as needed and can process long or streaming data without building all groups at once.” Apply this procedure: Measure when source items are requested and retain only the current group summary. The expected mechanism is: The loop can process one run at a time when handle consumes the group before continuing. For the budget list, add one near-miss that exposes calling list on the entire groupby result and claiming the workflow remains streaming. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers calling list on the entire groupby result and claiming the workflow remains streaming.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Measure when source items are requested and retain only the current group summary.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from Lazy reading limits memory?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing calling list on the entire groupby result and claiming the workflow remains streaming be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny CCA attendance with adjacent present, late and absent states. Include one ordinary case, one boundary and one deliberate failure caused by calling list on the entire groupby result and claiming the workflow remains streaming. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: groupby pulls input as needed and can process long or streaming data without building all groups at once. It shows a trace, not only a final value. The ordinary case should demonstrate “The loop can process one run at a time when handle consumes the group before continuing.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Measure when source items are requested and retain only the current group summary. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For Lazy reading limits memory, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
An empty iterable produces no groups; otherwise the first item establishes the initial current key and group. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is writing special-case code that duplicates the iterator contract incorrectly. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Test empty, one-item and two-key inputs before complex data.
For the The first item starts the first group chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on writing special-case code that duplicates the iterator contract incorrectly. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
list(groupby([]))
[(k,list(g)) for k,g in groupby([7])]Explained result. The empty case yields nothing; the singleton produces one key 7 with one item. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: revision tracker. Contrast the rule using topic attempts ordered by date and confidence band. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An empty iterable produces no groups; otherwise the first item establishes the initial current key and group.” Apply this procedure: Test empty, one-item and two-key inputs before complex data. The expected mechanism is: The empty case yields nothing; the singleton produces one key 7 with one item. For the revision tracker, add one near-miss that exposes writing special-case code that duplicates the iterator contract incorrectly. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: budget list. Stress-test the rule using transactions sorted by category before summarising. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An empty iterable produces no groups; otherwise the first item establishes the initial current key and group.” Apply this procedure: Test empty, one-item and two-key inputs before complex data. The expected mechanism is: The empty case yields nothing; the singleton produces one key 7 with one item. For the budget list, add one near-miss that exposes writing special-case code that duplicates the iterator contract incorrectly. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: text analysis. Explain the rule using consecutive words classified by length or initial. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An empty iterable produces no groups; otherwise the first item establishes the initial current key and group.” Apply this procedure: Test empty, one-item and two-key inputs before complex data. The expected mechanism is: The empty case yields nothing; the singleton produces one key 7 with one item. For the text analysis, add one near-miss that exposes writing special-case code that duplicates the iterator contract incorrectly. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: debug stream. Transfer the rule using a generator that prints whenever its next item is requested. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An empty iterable produces no groups; otherwise the first item establishes the initial current key and group.” Apply this procedure: Test empty, one-item and two-key inputs before complex data. The expected mechanism is: The empty case yields nothing; the singleton produces one key 7 with one item. For the debug stream, add one near-miss that exposes writing special-case code that duplicates the iterator contract incorrectly. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers writing special-case code that duplicates the iterator contract incorrectly.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Test empty, one-item and two-key inputs before complex data.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from The first item starts the first group?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing writing special-case code that duplicates the iterator contract incorrectly be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny science readings with runs of sensor status after threshold classification. Include one ordinary case, one boundary and one deliberate failure caused by writing special-case code that duplicates the iterator contract incorrectly. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: An empty iterable produces no groups; otherwise the first item establishes the initial current key and group. It shows a trace, not only a final value. The ordinary case should demonstrate “The empty case yields nothing; the singleton produces one key 7 with one item.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Test empty, one-item and two-key inputs before complex data. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For The first item starts the first group, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
A key value may reappear later and create another group after an intervening different key. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is building a dictionary from group pairs and silently overwriting an earlier run. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Preserve run order or aggregate explicitly according to the intended semantics.
For the Repeated keys can form several groups chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on building a dictionary from group pairs and silently overwriting an earlier run. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
[(k,''.join(g)) for k,g in groupby('AABBAA')]Explained result. The result is A:AA, B:BB, A:AA, retaining three runs rather than two categories. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: text analysis. Stress-test the rule using consecutive words classified by length or initial. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A key value may reappear later and create another group after an intervening different key.” Apply this procedure: Preserve run order or aggregate explicitly according to the intended semantics. The expected mechanism is: The result is A:AA, B:BB, A:AA, retaining three runs rather than two categories. For the text analysis, add one near-miss that exposes building a dictionary from group pairs and silently overwriting an earlier run. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: debug stream. Explain the rule using a generator that prints whenever its next item is requested. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A key value may reappear later and create another group after an intervening different key.” Apply this procedure: Preserve run order or aggregate explicitly according to the intended semantics. The expected mechanism is: The result is A:AA, B:BB, A:AA, retaining three runs rather than two categories. For the debug stream, add one near-miss that exposes building a dictionary from group pairs and silently overwriting an earlier run. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: homework log. Transfer the rule using consecutive subject labels and minutes studied. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A key value may reappear later and create another group after an intervening different key.” Apply this procedure: Preserve run order or aggregate explicitly according to the intended semantics. The expected mechanism is: The result is A:AA, B:BB, A:AA, retaining three runs rather than two categories. For the homework log, add one near-miss that exposes building a dictionary from group pairs and silently overwriting an earlier run. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: library shelf. Predict the rule using books ordered by section code and title. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A key value may reappear later and create another group after an intervening different key.” Apply this procedure: Preserve run order or aggregate explicitly according to the intended semantics. The expected mechanism is: The result is A:AA, B:BB, A:AA, retaining three runs rather than two categories. For the library shelf, add one near-miss that exposes building a dictionary from group pairs and silently overwriting an earlier run. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers building a dictionary from group pairs and silently overwriting an earlier run.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Preserve run order or aggregate explicitly according to the intended semantics.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from Repeated keys can form several groups?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing building a dictionary from group pairs and silently overwriting an earlier run be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny revision tracker with topic attempts ordered by date and confidence band. Include one ordinary case, one boundary and one deliberate failure caused by building a dictionary from group pairs and silently overwriting an earlier run. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: A key value may reappear later and create another group after an intervening different key. It shows a trace, not only a final value. The ordinary case should demonstrate “The result is A:AA, B:BB, A:AA, retaining three runs rather than two categories.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Preserve run order or aggregate explicitly according to the intended semantics. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For Repeated keys can form several groups, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
When key is omitted, each item itself supplies the comparison key for adjacent grouping. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is assuming omission means truthiness, type or a remembered previous custom key. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Write the equivalent identity function and test mixed values deliberately.
For the Default key is identity chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on assuming omission means truthiness, type or a remembered previous custom key. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
[(k,list(g)) for k,g in groupby([1,1,2,2,1])]Explained result. Adjacent equal integers form the groups 1, 2 and 1. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: homework log. Explain the rule using consecutive subject labels and minutes studied. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “When key is omitted, each item itself supplies the comparison key for adjacent grouping.” Apply this procedure: Write the equivalent identity function and test mixed values deliberately. The expected mechanism is: Adjacent equal integers form the groups 1, 2 and 1. For the homework log, add one near-miss that exposes assuming omission means truthiness, type or a remembered previous custom key. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: library shelf. Transfer the rule using books ordered by section code and title. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “When key is omitted, each item itself supplies the comparison key for adjacent grouping.” Apply this procedure: Write the equivalent identity function and test mixed values deliberately. The expected mechanism is: Adjacent equal integers form the groups 1, 2 and 1. For the library shelf, add one near-miss that exposes assuming omission means truthiness, type or a remembered previous custom key. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: CCA attendance. Predict the rule using adjacent present, late and absent states. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “When key is omitted, each item itself supplies the comparison key for adjacent grouping.” Apply this procedure: Write the equivalent identity function and test mixed values deliberately. The expected mechanism is: Adjacent equal integers form the groups 1, 2 and 1. For the CCA attendance, add one near-miss that exposes assuming omission means truthiness, type or a remembered previous custom key. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: science readings. Contrast the rule using runs of sensor status after threshold classification. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “When key is omitted, each item itself supplies the comparison key for adjacent grouping.” Apply this procedure: Write the equivalent identity function and test mixed values deliberately. The expected mechanism is: Adjacent equal integers form the groups 1, 2 and 1. For the science readings, add one near-miss that exposes assuming omission means truthiness, type or a remembered previous custom key. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers assuming omission means truthiness, type or a remembered previous custom key.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Write the equivalent identity function and test mixed values deliberately.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from Default key is identity?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing assuming omission means truthiness, type or a remembered previous custom key be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny budget list with transactions sorted by category before summarising. Include one ordinary case, one boundary and one deliberate failure caused by assuming omission means truthiness, type or a remembered previous custom key. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: When key is omitted, each item itself supplies the comparison key for adjacent grouping. It shows a trace, not only a final value. The ordinary case should demonstrate “Adjacent equal integers form the groups 1, 2 and 1.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Write the equivalent identity function and test mixed values deliberately. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For Default key is identity, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
A key function should return a stable result for each item and avoid side effects that make grouping depend on call history. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is using a counter, clock or mutable global inside key. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Call the key on fixtures separately and require deterministic outputs before grouping.
For the Pure stable keys keep reasoning sound chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on using a counter, clock or mutable global inside key. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
def band(score):
return 'high' if score>=75 else 'developing'Explained result. The band depends only on score, so adjacent boundary predictions remain reproducible. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: CCA attendance. Transfer the rule using adjacent present, late and absent states. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A key function should return a stable result for each item and avoid side effects that make grouping depend on call history.” Apply this procedure: Call the key on fixtures separately and require deterministic outputs before grouping. The expected mechanism is: The band depends only on score, so adjacent boundary predictions remain reproducible. For the CCA attendance, add one near-miss that exposes using a counter, clock or mutable global inside key. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: science readings. Predict the rule using runs of sensor status after threshold classification. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A key function should return a stable result for each item and avoid side effects that make grouping depend on call history.” Apply this procedure: Call the key on fixtures separately and require deterministic outputs before grouping. The expected mechanism is: The band depends only on score, so adjacent boundary predictions remain reproducible. For the science readings, add one near-miss that exposes using a counter, clock or mutable global inside key. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: revision tracker. Contrast the rule using topic attempts ordered by date and confidence band. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A key function should return a stable result for each item and avoid side effects that make grouping depend on call history.” Apply this procedure: Call the key on fixtures separately and require deterministic outputs before grouping. The expected mechanism is: The band depends only on score, so adjacent boundary predictions remain reproducible. For the revision tracker, add one near-miss that exposes using a counter, clock or mutable global inside key. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: budget list. Stress-test the rule using transactions sorted by category before summarising. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A key function should return a stable result for each item and avoid side effects that make grouping depend on call history.” Apply this procedure: Call the key on fixtures separately and require deterministic outputs before grouping. The expected mechanism is: The band depends only on score, so adjacent boundary predictions remain reproducible. For the budget list, add one near-miss that exposes using a counter, clock or mutable global inside key. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers using a counter, clock or mutable global inside key.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Call the key on fixtures separately and require deterministic outputs before grouping.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from Pure stable keys keep reasoning sound?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing using a counter, clock or mutable global inside key be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny text analysis with consecutive words classified by length or initial. Include one ordinary case, one boundary and one deliberate failure caused by using a counter, clock or mutable global inside key. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: A key function should return a stable result for each item and avoid side effects that make grouping depend on call history. It shows a trace, not only a final value. The ordinary case should demonstrate “The band depends only on score, so adjacent boundary predictions remain reproducible.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Call the key on fixtures separately and require deterministic outputs before grouping. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For Pure stable keys keep reasoning sound, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
operator.itemgetter can select a tuple or mapping field without a lambda and helps reuse exactly the same key for sorting and grouping. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is using different numeric positions in sort and group expressions. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Bind the getter to one named variable and test one record before processing the collection.
For the itemgetter makes record keys explicit chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on using different numeric positions in sort and group expressions. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
from operator import itemgetter
key=itemgetter('subject')
rows=sorted(rows,key=key)Explained result. The same subject extractor controls adjacency and group boundaries. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: revision tracker. Predict the rule using topic attempts ordered by date and confidence band. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “operator.itemgetter can select a tuple or mapping field without a lambda and helps reuse exactly the same key for sorting and grouping.” Apply this procedure: Bind the getter to one named variable and test one record before processing the collection. The expected mechanism is: The same subject extractor controls adjacency and group boundaries. For the revision tracker, add one near-miss that exposes using different numeric positions in sort and group expressions. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: budget list. Contrast the rule using transactions sorted by category before summarising. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “operator.itemgetter can select a tuple or mapping field without a lambda and helps reuse exactly the same key for sorting and grouping.” Apply this procedure: Bind the getter to one named variable and test one record before processing the collection. The expected mechanism is: The same subject extractor controls adjacency and group boundaries. For the budget list, add one near-miss that exposes using different numeric positions in sort and group expressions. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: text analysis. Stress-test the rule using consecutive words classified by length or initial. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “operator.itemgetter can select a tuple or mapping field without a lambda and helps reuse exactly the same key for sorting and grouping.” Apply this procedure: Bind the getter to one named variable and test one record before processing the collection. The expected mechanism is: The same subject extractor controls adjacency and group boundaries. For the text analysis, add one near-miss that exposes using different numeric positions in sort and group expressions. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: debug stream. Explain the rule using a generator that prints whenever its next item is requested. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “operator.itemgetter can select a tuple or mapping field without a lambda and helps reuse exactly the same key for sorting and grouping.” Apply this procedure: Bind the getter to one named variable and test one record before processing the collection. The expected mechanism is: The same subject extractor controls adjacency and group boundaries. For the debug stream, add one near-miss that exposes using different numeric positions in sort and group expressions. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers using different numeric positions in sort and group expressions.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Bind the getter to one named variable and test one record before processing the collection.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from itemgetter makes record keys explicit?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing using different numeric positions in sort and group expressions be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny debug stream with a generator that prints whenever its next item is requested. Include one ordinary case, one boundary and one deliberate failure caused by using different numeric positions in sort and group expressions. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: operator.itemgetter can select a tuple or mapping field without a lambda and helps reuse exactly the same key for sorting and grouping. It shows a trace, not only a final value. The ordinary case should demonstrate “The same subject extractor controls adjacency and group boundaries.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Bind the getter to one named variable and test one record before processing the collection. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For itemgetter makes record keys explicit, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
operator.attrgetter selects an attribute from objects, including simple dataclass instances, for repeated sort-and-group use. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is grouping objects by their whole identity when one attribute is intended. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Choose the domain attribute, make its ordering policy clear and reuse the getter.
For the attrgetter supports object records chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on grouping objects by their whole identity when one attribute is intended. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
from operator import attrgetter
key=attrgetter('status')
items=sorted(items,key=key)Explained result. Items with the same status become adjacent and therefore share a group. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: text analysis. Contrast the rule using consecutive words classified by length or initial. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “operator.attrgetter selects an attribute from objects, including simple dataclass instances, for repeated sort-and-group use.” Apply this procedure: Choose the domain attribute, make its ordering policy clear and reuse the getter. The expected mechanism is: Items with the same status become adjacent and therefore share a group. For the text analysis, add one near-miss that exposes grouping objects by their whole identity when one attribute is intended. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: debug stream. Stress-test the rule using a generator that prints whenever its next item is requested. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “operator.attrgetter selects an attribute from objects, including simple dataclass instances, for repeated sort-and-group use.” Apply this procedure: Choose the domain attribute, make its ordering policy clear and reuse the getter. The expected mechanism is: Items with the same status become adjacent and therefore share a group. For the debug stream, add one near-miss that exposes grouping objects by their whole identity when one attribute is intended. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: homework log. Explain the rule using consecutive subject labels and minutes studied. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “operator.attrgetter selects an attribute from objects, including simple dataclass instances, for repeated sort-and-group use.” Apply this procedure: Choose the domain attribute, make its ordering policy clear and reuse the getter. The expected mechanism is: Items with the same status become adjacent and therefore share a group. For the homework log, add one near-miss that exposes grouping objects by their whole identity when one attribute is intended. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: library shelf. Transfer the rule using books ordered by section code and title. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “operator.attrgetter selects an attribute from objects, including simple dataclass instances, for repeated sort-and-group use.” Apply this procedure: Choose the domain attribute, make its ordering policy clear and reuse the getter. The expected mechanism is: Items with the same status become adjacent and therefore share a group. For the library shelf, add one near-miss that exposes grouping objects by their whole identity when one attribute is intended. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers grouping objects by their whole identity when one attribute is intended.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Choose the domain attribute, make its ordering policy clear and reuse the getter.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from attrgetter supports object records?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing grouping objects by their whole identity when one attribute is intended be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny homework log with consecutive subject labels and minutes studied. Include one ordinary case, one boundary and one deliberate failure caused by grouping objects by their whole identity when one attribute is intended. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: operator.attrgetter selects an attribute from objects, including simple dataclass instances, for repeated sort-and-group use. It shows a trace, not only a final value. The ordinary case should demonstrate “Items with the same status become adjacent and therefore share a group.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Choose the domain attribute, make its ordering policy clear and reuse the getter. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For attrgetter supports object records, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
CHAPTER 13 OF 20 . Debug and verify
13. Normalising text changes the grouping contract
Case-folding, trimming or Unicode normalisation can make labels share keys even while original values remain distinct. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is normalising in one stage and forgetting which original distinctions were collapsed. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Keep raw values in the group and document the exact normalisation used for keys.
For the Normalising text changes the grouping contract chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on normalising in one stage and forgetting which original distinctions were collapsed. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
key=lambda s:s.strip().casefold()
[(k,list(g)) for k,g in groupby(sorted(names,key=key),key)]Explained result. Labels differing only by surrounding space or case can enter the same normalised category. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: homework log. Stress-test the rule using consecutive subject labels and minutes studied. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Case-folding, trimming or Unicode normalisation can make labels share keys even while original values remain distinct.” Apply this procedure: Keep raw values in the group and document the exact normalisation used for keys. The expected mechanism is: Labels differing only by surrounding space or case can enter the same normalised category. For the homework log, add one near-miss that exposes normalising in one stage and forgetting which original distinctions were collapsed. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: library shelf. Explain the rule using books ordered by section code and title. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Case-folding, trimming or Unicode normalisation can make labels share keys even while original values remain distinct.” Apply this procedure: Keep raw values in the group and document the exact normalisation used for keys. The expected mechanism is: Labels differing only by surrounding space or case can enter the same normalised category. For the library shelf, add one near-miss that exposes normalising in one stage and forgetting which original distinctions were collapsed. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: CCA attendance. Transfer the rule using adjacent present, late and absent states. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Case-folding, trimming or Unicode normalisation can make labels share keys even while original values remain distinct.” Apply this procedure: Keep raw values in the group and document the exact normalisation used for keys. The expected mechanism is: Labels differing only by surrounding space or case can enter the same normalised category. For the CCA attendance, add one near-miss that exposes normalising in one stage and forgetting which original distinctions were collapsed. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: science readings. Predict the rule using runs of sensor status after threshold classification. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Case-folding, trimming or Unicode normalisation can make labels share keys even while original values remain distinct.” Apply this procedure: Keep raw values in the group and document the exact normalisation used for keys. The expected mechanism is: Labels differing only by surrounding space or case can enter the same normalised category. For the science readings, add one near-miss that exposes normalising in one stage and forgetting which original distinctions were collapsed. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers normalising in one stage and forgetting which original distinctions were collapsed.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Keep raw values in the group and document the exact normalisation used for keys.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from Normalising text changes the grouping contract?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing normalising in one stage and forgetting which original distinctions were collapsed be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny library shelf with books ordered by section code and title. Include one ordinary case, one boundary and one deliberate failure caused by normalising in one stage and forgetting which original distinctions were collapsed. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Case-folding, trimming or Unicode normalisation can make labels share keys even while original values remain distinct. It shows a trace, not only a final value. The ordinary case should demonstrate “Labels differing only by surrounding space or case can enter the same normalised category.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Keep raw values in the group and document the exact normalisation used for keys. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For Normalising text changes the grouping contract, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
The key function selects boundaries, but the group iterator yields the original input objects rather than transformed keys. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is expecting each group to contain only key values. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Inspect one key and one first group item separately.
For the Group values are original items chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on expecting each group to contain only key values. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
for length,words in groupby(['a','to','be'],key=len):
print(length,list(words))Explained result. The keys are lengths while group members remain the original strings. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: CCA attendance. Explain the rule using adjacent present, late and absent states. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “The key function selects boundaries, but the group iterator yields the original input objects rather than transformed keys.” Apply this procedure: Inspect one key and one first group item separately. The expected mechanism is: The keys are lengths while group members remain the original strings. For the CCA attendance, add one near-miss that exposes expecting each group to contain only key values. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: science readings. Transfer the rule using runs of sensor status after threshold classification. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “The key function selects boundaries, but the group iterator yields the original input objects rather than transformed keys.” Apply this procedure: Inspect one key and one first group item separately. The expected mechanism is: The keys are lengths while group members remain the original strings. For the science readings, add one near-miss that exposes expecting each group to contain only key values. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: revision tracker. Predict the rule using topic attempts ordered by date and confidence band. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “The key function selects boundaries, but the group iterator yields the original input objects rather than transformed keys.” Apply this procedure: Inspect one key and one first group item separately. The expected mechanism is: The keys are lengths while group members remain the original strings. For the revision tracker, add one near-miss that exposes expecting each group to contain only key values. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: budget list. Contrast the rule using transactions sorted by category before summarising. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “The key function selects boundaries, but the group iterator yields the original input objects rather than transformed keys.” Apply this procedure: Inspect one key and one first group item separately. The expected mechanism is: The keys are lengths while group members remain the original strings. For the budget list, add one near-miss that exposes expecting each group to contain only key values. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers expecting each group to contain only key values.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Inspect one key and one first group item separately.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from Group values are original items?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing expecting each group to contain only key values be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny CCA attendance with adjacent present, late and absent states. Include one ordinary case, one boundary and one deliberate failure caused by expecting each group to contain only key values. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: The key function selects boundaries, but the group iterator yields the original input objects rather than transformed keys. It shows a trace, not only a final value. The ordinary case should demonstrate “The keys are lengths while group members remain the original strings.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Inspect one key and one first group item separately. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For Group values are original items, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
Counts, sums, minima and summaries are explicit reductions over each group iterator. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is iterating a group twice after the first reduction has exhausted it. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Perform all required statistics in one pass or materialise the current group once.
For the Aggregating each run deliberately chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on iterating a group twice after the first reduction has exhausted it. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
for key,g in groupby(rows,key=category):
total=sum(row.amount for row in g)Explained result. The sum consumes that run and produces one total for the current consecutive category. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: revision tracker. Transfer the rule using topic attempts ordered by date and confidence band. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Counts, sums, minima and summaries are explicit reductions over each group iterator.” Apply this procedure: Perform all required statistics in one pass or materialise the current group once. The expected mechanism is: The sum consumes that run and produces one total for the current consecutive category. For the revision tracker, add one near-miss that exposes iterating a group twice after the first reduction has exhausted it. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: budget list. Predict the rule using transactions sorted by category before summarising. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Counts, sums, minima and summaries are explicit reductions over each group iterator.” Apply this procedure: Perform all required statistics in one pass or materialise the current group once. The expected mechanism is: The sum consumes that run and produces one total for the current consecutive category. For the budget list, add one near-miss that exposes iterating a group twice after the first reduction has exhausted it. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: text analysis. Contrast the rule using consecutive words classified by length or initial. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Counts, sums, minima and summaries are explicit reductions over each group iterator.” Apply this procedure: Perform all required statistics in one pass or materialise the current group once. The expected mechanism is: The sum consumes that run and produces one total for the current consecutive category. For the text analysis, add one near-miss that exposes iterating a group twice after the first reduction has exhausted it. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: debug stream. Stress-test the rule using a generator that prints whenever its next item is requested. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Counts, sums, minima and summaries are explicit reductions over each group iterator.” Apply this procedure: Perform all required statistics in one pass or materialise the current group once. The expected mechanism is: The sum consumes that run and produces one total for the current consecutive category. For the debug stream, add one near-miss that exposes iterating a group twice after the first reduction has exhausted it. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers iterating a group twice after the first reduction has exhausted it.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Perform all required statistics in one pass or materialise the current group once.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from Aggregating each run deliberately?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing iterating a group twice after the first reduction has exhausted it be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny science readings with runs of sensor status after threshold classification. Include one ordinary case, one boundary and one deliberate failure caused by iterating a group twice after the first reduction has exhausted it. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Counts, sums, minima and summaries are explicit reductions over each group iterator. It shows a trace, not only a final value. The ordinary case should demonstrate “The sum consumes that run and produces one total for the current consecutive category.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Perform all required statistics in one pass or materialise the current group once. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For Aggregating each run deliberately, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
groupby can accept an infinite iterable, but a group that never changes key is itself infinite and prevents the outer iterator reaching another group. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is calling list on a group whose key may never change. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Bound consumption or design a source whose run ends are guaranteed.
For the Infinite streams need finite runs chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on calling list on a group whose key may never change. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
for key,g in groupby(sensor_stream(),key=status):
for reading in islice(g,100): process(reading)Explained result. The inner bound prevents one long status run from consuming without limit, though it also defines an application policy. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: text analysis. Predict the rule using consecutive words classified by length or initial. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “groupby can accept an infinite iterable, but a group that never changes key is itself infinite and prevents the outer iterator reaching another group.” Apply this procedure: Bound consumption or design a source whose run ends are guaranteed. The expected mechanism is: The inner bound prevents one long status run from consuming without limit, though it also defines an application policy. For the text analysis, add one near-miss that exposes calling list on a group whose key may never change. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: debug stream. Contrast the rule using a generator that prints whenever its next item is requested. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “groupby can accept an infinite iterable, but a group that never changes key is itself infinite and prevents the outer iterator reaching another group.” Apply this procedure: Bound consumption or design a source whose run ends are guaranteed. The expected mechanism is: The inner bound prevents one long status run from consuming without limit, though it also defines an application policy. For the debug stream, add one near-miss that exposes calling list on a group whose key may never change. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: homework log. Stress-test the rule using consecutive subject labels and minutes studied. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “groupby can accept an infinite iterable, but a group that never changes key is itself infinite and prevents the outer iterator reaching another group.” Apply this procedure: Bound consumption or design a source whose run ends are guaranteed. The expected mechanism is: The inner bound prevents one long status run from consuming without limit, though it also defines an application policy. For the homework log, add one near-miss that exposes calling list on a group whose key may never change. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: library shelf. Explain the rule using books ordered by section code and title. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “groupby can accept an infinite iterable, but a group that never changes key is itself infinite and prevents the outer iterator reaching another group.” Apply this procedure: Bound consumption or design a source whose run ends are guaranteed. The expected mechanism is: The inner bound prevents one long status run from consuming without limit, though it also defines an application policy. For the library shelf, add one near-miss that exposes calling list on a group whose key may never change. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers calling list on a group whose key may never change.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Bound consumption or design a source whose run ends are guaranteed.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from Infinite streams need finite runs?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing calling list on a group whose key may never change be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny revision tracker with topic attempts ordered by date and confidence band. Include one ordinary case, one boundary and one deliberate failure caused by calling list on a group whose key may never change. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: groupby can accept an infinite iterable, but a group that never changes key is itself infinite and prevents the outer iterator reaching another group. It shows a trace, not only a final value. The ordinary case should demonstrate “The inner bound prevents one long status run from consuming without limit, though it also defines an application policy.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Bound consumption or design a source whose run ends are guaranteed. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For Infinite streams need finite runs, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
Consecutive grouping can encode repeated values as a key plus run length while preserving sequence structure. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is sorting before run-length encoding and destroying the sequence being compressed. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Keep original order and count each group exactly once.
For the Run-length encoding is a natural use chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on sorting before run-length encoding and destroying the sequence being compressed. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
encoded=[(k,sum(1 for _ in g)) for k,g in groupby('AAABCC')]Explained result. The encoding is A3, B1, C2 because the task concerns consecutive repetition. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: homework log. Contrast the rule using consecutive subject labels and minutes studied. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Consecutive grouping can encode repeated values as a key plus run length while preserving sequence structure.” Apply this procedure: Keep original order and count each group exactly once. The expected mechanism is: The encoding is A3, B1, C2 because the task concerns consecutive repetition. For the homework log, add one near-miss that exposes sorting before run-length encoding and destroying the sequence being compressed. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: library shelf. Stress-test the rule using books ordered by section code and title. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Consecutive grouping can encode repeated values as a key plus run length while preserving sequence structure.” Apply this procedure: Keep original order and count each group exactly once. The expected mechanism is: The encoding is A3, B1, C2 because the task concerns consecutive repetition. For the library shelf, add one near-miss that exposes sorting before run-length encoding and destroying the sequence being compressed. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: CCA attendance. Explain the rule using adjacent present, late and absent states. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Consecutive grouping can encode repeated values as a key plus run length while preserving sequence structure.” Apply this procedure: Keep original order and count each group exactly once. The expected mechanism is: The encoding is A3, B1, C2 because the task concerns consecutive repetition. For the CCA attendance, add one near-miss that exposes sorting before run-length encoding and destroying the sequence being compressed. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: science readings. Transfer the rule using runs of sensor status after threshold classification. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Consecutive grouping can encode repeated values as a key plus run length while preserving sequence structure.” Apply this procedure: Keep original order and count each group exactly once. The expected mechanism is: The encoding is A3, B1, C2 because the task concerns consecutive repetition. For the science readings, add one near-miss that exposes sorting before run-length encoding and destroying the sequence being compressed. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers sorting before run-length encoding and destroying the sequence being compressed.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Keep original order and count each group exactly once.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from Run-length encoding is a natural use?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing sorting before run-length encoding and destroying the sequence being compressed be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny budget list with transactions sorted by category before summarising. Include one ordinary case, one boundary and one deliberate failure caused by sorting before run-length encoding and destroying the sequence being compressed. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Consecutive grouping can encode repeated values as a key plus run length while preserving sequence structure. It shows a trace, not only a final value. The ordinary case should demonstrate “The encoding is A3, B1, C2 because the task concerns consecutive repetition.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Keep original order and count each group exactly once. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For Run-length encoding is a natural use, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
CHAPTER 18 OF 20 . Transfer with judgment
18. Bucket dictionaries solve a different job
defaultdict or ordinary dictionaries collect all items per key regardless of adjacency, often matching unsorted category bucketing better. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is forcing groupby onto unsorted data merely to avoid a dictionary. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Compare required order, memory and streaming constraints before selecting the structure.
For the Bucket dictionaries solve a different job chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on forcing groupby onto unsorted data merely to avoid a dictionary. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
from collections import defaultdict
buckets=defaultdict(list)
for item in data:buckets[key(item)].append(item)Explained result. Every repeated key reaches one bucket even when matching items are separated in the input. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: CCA attendance. Stress-test the rule using adjacent present, late and absent states. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “defaultdict or ordinary dictionaries collect all items per key regardless of adjacency, often matching unsorted category bucketing better.” Apply this procedure: Compare required order, memory and streaming constraints before selecting the structure. The expected mechanism is: Every repeated key reaches one bucket even when matching items are separated in the input. For the CCA attendance, add one near-miss that exposes forcing groupby onto unsorted data merely to avoid a dictionary. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: science readings. Explain the rule using runs of sensor status after threshold classification. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “defaultdict or ordinary dictionaries collect all items per key regardless of adjacency, often matching unsorted category bucketing better.” Apply this procedure: Compare required order, memory and streaming constraints before selecting the structure. The expected mechanism is: Every repeated key reaches one bucket even when matching items are separated in the input. For the science readings, add one near-miss that exposes forcing groupby onto unsorted data merely to avoid a dictionary. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: revision tracker. Transfer the rule using topic attempts ordered by date and confidence band. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “defaultdict or ordinary dictionaries collect all items per key regardless of adjacency, often matching unsorted category bucketing better.” Apply this procedure: Compare required order, memory and streaming constraints before selecting the structure. The expected mechanism is: Every repeated key reaches one bucket even when matching items are separated in the input. For the revision tracker, add one near-miss that exposes forcing groupby onto unsorted data merely to avoid a dictionary. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: budget list. Predict the rule using transactions sorted by category before summarising. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “defaultdict or ordinary dictionaries collect all items per key regardless of adjacency, often matching unsorted category bucketing better.” Apply this procedure: Compare required order, memory and streaming constraints before selecting the structure. The expected mechanism is: Every repeated key reaches one bucket even when matching items are separated in the input. For the budget list, add one near-miss that exposes forcing groupby onto unsorted data merely to avoid a dictionary. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers forcing groupby onto unsorted data merely to avoid a dictionary.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Compare required order, memory and streaming constraints before selecting the structure.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from Bucket dictionaries solve a different job?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing forcing groupby onto unsorted data merely to avoid a dictionary be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny text analysis with consecutive words classified by length or initial. Include one ordinary case, one boundary and one deliberate failure caused by forcing groupby onto unsorted data merely to avoid a dictionary. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: defaultdict or ordinary dictionaries collect all items per key regardless of adjacency, often matching unsorted category bucketing better. It shows a trace, not only a final value. The ordinary case should demonstrate “Every repeated key reaches one bucket even when matching items are separated in the input.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Compare required order, memory and streaming constraints before selecting the structure. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For Bucket dictionaries solve a different job, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
A tracing generator and explicit key log reveal when groupby pulls ahead and why an earlier group is empty after outer advancement. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is debugging only the final nested list and missing iterator timing. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Print each source yield, key call and outer-loop step in the smallest failing case.
For the Debug by exposing source consumption chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on debugging only the final nested list and missing iterator timing. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
def traced(xs):
for x in xs:
print('yield',x);yield xExplained result. The log makes lazy consumption and the shared underlying iterator observable. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: revision tracker. Explain the rule using topic attempts ordered by date and confidence band. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A tracing generator and explicit key log reveal when groupby pulls ahead and why an earlier group is empty after outer advancement.” Apply this procedure: Print each source yield, key call and outer-loop step in the smallest failing case. The expected mechanism is: The log makes lazy consumption and the shared underlying iterator observable. For the revision tracker, add one near-miss that exposes debugging only the final nested list and missing iterator timing. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: budget list. Transfer the rule using transactions sorted by category before summarising. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A tracing generator and explicit key log reveal when groupby pulls ahead and why an earlier group is empty after outer advancement.” Apply this procedure: Print each source yield, key call and outer-loop step in the smallest failing case. The expected mechanism is: The log makes lazy consumption and the shared underlying iterator observable. For the budget list, add one near-miss that exposes debugging only the final nested list and missing iterator timing. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: text analysis. Predict the rule using consecutive words classified by length or initial. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A tracing generator and explicit key log reveal when groupby pulls ahead and why an earlier group is empty after outer advancement.” Apply this procedure: Print each source yield, key call and outer-loop step in the smallest failing case. The expected mechanism is: The log makes lazy consumption and the shared underlying iterator observable. For the text analysis, add one near-miss that exposes debugging only the final nested list and missing iterator timing. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: debug stream. Contrast the rule using a generator that prints whenever its next item is requested. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A tracing generator and explicit key log reveal when groupby pulls ahead and why an earlier group is empty after outer advancement.” Apply this procedure: Print each source yield, key call and outer-loop step in the smallest failing case. The expected mechanism is: The log makes lazy consumption and the shared underlying iterator observable. For the debug stream, add one near-miss that exposes debugging only the final nested list and missing iterator timing. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers debugging only the final nested list and missing iterator timing.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Print each source yield, key call and outer-loop step in the smallest failing case.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from Debug by exposing source consumption?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing debugging only the final nested list and missing iterator timing be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny debug stream with a generator that prints whenever its next item is requested. Include one ordinary case, one boundary and one deliberate failure caused by debugging only the final nested list and missing iterator timing. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: A tracing generator and explicit key log reveal when groupby pulls ahead and why an earlier group is empty after outer advancement. It shows a trace, not only a final value. The ordinary case should demonstrate “The log makes lazy consumption and the shared underlying iterator observable.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Print each source yield, key call and outer-loop step in the smallest failing case. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For Debug by exposing source consumption, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
Use groupby when consecutive runs matter or when data is already ordered by the grouping key; use sorting plus groupby, a dictionary or a data tool for other jobs. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is choosing by a familiar function name rather than the data-order contract. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Write the desired output order, adjacency rule, memory limit and aggregation before coding.
For the A decision framework for groupby chapter on Python itertools.groupby, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on choosing by a familiar function name rather than the data-order contract. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.
Core worked example
# Ask: runs, ordered categories, or global buckets?Explained result. Mastery is selecting the structure whose grouping semantics match the reader job and proving it with a counterexample. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: text analysis. Transfer the rule using consecutive words classified by length or initial. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Use groupby when consecutive runs matter or when data is already ordered by the grouping key; use sorting plus groupby, a dictionary or a data tool for other jobs.” Apply this procedure: Write the desired output order, adjacency rule, memory limit and aggregation before coding. The expected mechanism is: Mastery is selecting the structure whose grouping semantics match the reader job and proving it with a counterexample. For the text analysis, add one near-miss that exposes choosing by a familiar function name rather than the data-order contract. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: debug stream. Predict the rule using a generator that prints whenever its next item is requested. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Use groupby when consecutive runs matter or when data is already ordered by the grouping key; use sorting plus groupby, a dictionary or a data tool for other jobs.” Apply this procedure: Write the desired output order, adjacency rule, memory limit and aggregation before coding. The expected mechanism is: Mastery is selecting the structure whose grouping semantics match the reader job and proving it with a counterexample. For the debug stream, add one near-miss that exposes choosing by a familiar function name rather than the data-order contract. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: homework log. Contrast the rule using consecutive subject labels and minutes studied. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Use groupby when consecutive runs matter or when data is already ordered by the grouping key; use sorting plus groupby, a dictionary or a data tool for other jobs.” Apply this procedure: Write the desired output order, adjacency rule, memory limit and aggregation before coding. The expected mechanism is: Mastery is selecting the structure whose grouping semantics match the reader job and proving it with a counterexample. For the homework log, add one near-miss that exposes choosing by a familiar function name rather than the data-order contract. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: library shelf. Stress-test the rule using books ordered by section code and title. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Use groupby when consecutive runs matter or when data is already ordered by the grouping key; use sorting plus groupby, a dictionary or a data tool for other jobs.” Apply this procedure: Write the desired output order, adjacency rule, memory limit and aggregation before coding. The expected mechanism is: Mastery is selecting the structure whose grouping semantics match the reader job and proving it with a counterexample. For the library shelf, add one near-miss that exposes choosing by a familiar function name rather than the data-order contract. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers choosing by a familiar function name rather than the data-order contract.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Write the desired output order, adjacency rule, memory limit and aggregation before coding.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final Python itertools.groupby syntax. For this chapter, useful prompts are: “What did you expect from A decision framework for groupby?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing choosing by a familiar function name rather than the data-order contract be made smaller?” The learner, not the parent, should supply the technical explanation.
Practice with an explained answer
Question. Build a tiny homework log with consecutive subject labels and minutes studied. Include one ordinary case, one boundary and one deliberate failure caused by choosing by a familiar function name rather than the data-order contract. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Use groupby when consecutive runs matter or when data is already ordered by the grouping key; use sorting plus groupby, a dictionary or a data tool for other jobs. It shows a trace, not only a final value. The ordinary case should demonstrate “Mastery is selecting the structure whose grouping semantics match the reader job and proving it with a counterexample.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Write the desired output order, adjacency rule, memory limit and aggregation before coding. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
For A decision framework for groupby, separate the documented Python itertools.groupby mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.
Previous chapter . Contents . Next chapter
Parent guide: choose the next useful step
Start with evidence, not a label such as careless. Ask for one prediction and one trace. If the first transition is wrong, rebuild the model. If the model is sound but syntax fails, practise reference use. If routine cases are correct but boundaries fail, vary ties, defaults, unsupported inputs, ownership or missing paths. If explanations transfer, move to a small project.
Keep a weekly record with four lines: concept, prediction, observed difference and next test. Stop when fatigue replaces reasoning. A smaller case tomorrow is more useful than another hour of copying tonight.
Seek specialist help when cause and effect remain invisible after examples are reduced, when accessibility or data-loss implications are unclear, or when an important repository, database or application state may be at risk. Good support should make the learner’s reasoning more independent.
Capstone practice with explained routes
1. homework log: model, boundary and recovery
Create a small homework log using consecutive subject labels and minutes studied. Combine “Consecutive runs are the central model” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: groupby starts a new group whenever the key value changes while reading the iterable from left to right. Apply: Write the key beside every item and draw a boundary only where adjacent keys differ. Verify: The result has A, B and A groups because the final A begins a new consecutive run. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
2. library shelf: model, boundary and recovery
Create a small library shelf using books ordered by section code and title. Combine “groupby is not SQL GROUP BY” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: The iterator reports runs and does not automatically calculate counts, sums or one bucket per distinct key. Apply: State whether the task is run detection, category bucketing or aggregation before choosing the tool. Verify: This counts adjacent runs; on AABAA it would report two separate A counts. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
3. CCA attendance: model, boundary and recovery
Create a small CCA attendance using adjacent present, late and absent states. Combine “The first item starts the first group” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: An empty iterable produces no groups; otherwise the first item establishes the initial current key and group. Apply: Test empty, one-item and two-key inputs before complex data. Verify: The empty case yields nothing; the singleton produces one key 7 with one item. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
4. science readings: model, boundary and recovery
Create a small science readings using runs of sensor status after threshold classification. Combine “Pure stable keys keep reasoning sound” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: A key function should return a stable result for each item and avoid side effects that make grouping depend on call history. Apply: Call the key on fixtures separately and require deterministic outputs before grouping. Verify: The band depends only on score, so adjacent boundary predictions remain reproducible. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
5. revision tracker: model, boundary and recovery
Create a small revision tracker using topic attempts ordered by date and confidence band. Combine “Normalising text changes the grouping contract” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: Case-folding, trimming or Unicode normalisation can make labels share keys even while original values remain distinct. Apply: Keep raw values in the group and document the exact normalisation used for keys. Verify: Labels differing only by surrounding space or case can enter the same normalised category. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
6. budget list: model, boundary and recovery
Create a small budget list using transactions sorted by category before summarising. Combine “Infinite streams need finite runs” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: groupby can accept an infinite iterable, but a group that never changes key is itself infinite and prevents the outer iterator reaching another group. Apply: Bound consumption or design a source whose run ends are guaranteed. Verify: The inner bound prevents one long status run from consuming without limit, though it also defines an application policy. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
7. text analysis: model, boundary and recovery
Create a small text analysis using consecutive words classified by length or initial. Combine “Debug by exposing source consumption” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: A tracing generator and explicit key log reveal when groupby pulls ahead and why an earlier group is empty after outer advancement. Apply: Print each source yield, key call and outer-loop step in the smallest failing case. Verify: The log makes lazy consumption and the shared underlying iterator observable. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
8. debug stream: model, boundary and recovery
Create a small debug stream using a generator that prints whenever its next item is requested. Combine “The key function defines equality” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: Each item is transformed by key, and consecutive transformed values are compared to decide group boundaries. Apply: Make a two-column item-to-key table before consuming the groups. Verify: The lengths form runs 3 then 4, so the words are grouped by adjacent length values. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
Frequently asked questions
How long should a practice session be?
Use one complete prediction–observation–explanation cycle while attention remains good. Ten to twenty focused minutes can be enough.
Should every option or function be memorised?
No. Memorise the governing distinctions and practise retrieving the official reference. Understanding means predicting and explaining, not reciting a parameter list.
What if the result is correct but the explanation is weak?
Treat it as partial success. Ask for a trace and change one boundary. A reliable model survives controlled variation.
Is the shortest solution the best?
Not automatically. Prefer the solution whose semantics, failure modes and maintenance cost are easiest to justify for the actual project.
When should official documentation be used?
Use it whenever syntax, supported types, SQL dialect behaviour or Git version details matter. Primary documentation settles the current contract.
How can a parent help without technical expertise?
Ask what was predicted, where the first difference appeared, what evidence matters and which smaller example could isolate it.
How do we test transfer?
Change the context, vocabulary and one boundary. Require the learner to identify the invariant before using a tool.
What should be saved after practice?
Keep the corrected rule, one trace, one boundary case and the next question. Avoid storing pages of unexplained output.
Can these exercises replace backups?
No. Use disposable examples and proper backups. Learning should not endanger schoolwork, repositories or personal data.
What counts as mastery?
The learner can predict, verify, diagnose, recover and justify a choice across more than one context, while knowing when to consult the current reference.

