eduKatePunggol · Practical learning guide
Find your next learning step
Choose a route through Python Sorting Keys to understand the mechanism, check a worked example and plan the next practice.
Full chapter index · Practice and parent questions · How Studying Works
Your child has written a Python program that produces every correct record, yet the report still looks wrong. Scores run from small to large when the task asks for the highest first. Names with capital letters appear in surprising places. Two students with the same score change places after a second operation. If you are looking for a useful Python learning exercise in Punggol, this is a wonderfully concrete problem: make the ordering rule visible before trying another line of code.
Python sorting keys let a program order complete records by a chosen feature. In sorted(records, key=...), the key is a callable that extracts the comparison value from each record; the returned list still contains the records. A learner who understands that distinction can build a sensible report instead of accidentally replacing the data with scores or names. Start with three fictional records, state their expected order aloud and compare that prediction with the program.
For a Punggol family fitting coding practice around school, CCA and homework, a short report can be more useful than a large unfinished application. This guide teaches Python sorted(), list.sort(), tuple keys and tie rules through a fictional reading challenge. It is an enrichment lesson, not a claim that these features are required in every school syllabus or offered in a particular tuition class. Use the routes above to find the difficulty your learner actually has.
Choose a chapter
Keep records and keys clear · 1–4
Set direction and tie rules · 5–8
Handle comparison conditions · 9–12
Validate and test · 13–16
CHAPTER 1 OF 20 · Keep records and keys clear
1. Give the report a rule before giving it code
Imagine a reading challenge with three fictional participants. Each record contains a display name, a book count and an entry number. The entry number is a label assigned when a record is created. It will help us recognise a record after sorting; it does not measure a child's ability.
records = [
{"name": "Mina", "books": 6, "entry": 1},
{"name": "Arun", "books": 9, "entry": 2},
{"name": "Lena", "books": 6, "entry": 3},
]
The first brief is simple: show the largest book count first and keep equal counts in their original order. The expected entry sequence is therefore 2, 1, 3. Ask the learner to write that sequence before opening the editor. It becomes an independent check, rather than an explanation invented after seeing an output.
This distinction matters when a child says, “The computer sorted it, so it must be correct.” The computer followed an instruction. Whether that instruction matches the report's purpose is a separate question. A perfectly executed alphabetical sort would fail this brief.
counts = [6, 9, 6]
ordered_counts = sorted(counts)
print(ordered_counts) # [6, 6, 9]
print(counts) # [6, 9, 6]
sorted() makes a new list. Here, the source list retains its order. This makes it suitable when one piece of data needs several views, such as registration order and a reading report. Keep the names of those views clear: records and report communicate different jobs better than a and b.
“New list” does not mean that every object inside it has been deeply copied. When the items are dictionaries, the new list contains references to those same dictionaries. Editing one record's book count through the report can therefore affect the source record. Sorting changes the arrangement; it does not create an independent database.
A parent can check the idea without knowing Python. Ask, “If we arrange three record cards on another table, have we made three new people?” The answer helps distinguish a different view from different underlying information.
counts = [6, 9, 6]
result = counts.sort()
print(counts) # [6, 6, 9]
print(result) # None
list.sort() rearranges that list and returns None. A common beginner mistake is report = records.sort(...), followed by confusion when report is not a list. Repair the misunderstanding before repairing the syntax: this method performs a change, whereas sorted() supplies a new result.
Choose the operation deliberately. If registration order must remain available, a separate sorted view is straightforward. If the list's own order should become the report order and no other code needs the previous arrangement, in-place sorting may be appropriate.
Do not treat this as a contest to use the shortest expression. The useful question is who else holds the list and what those readers expect. In a small practice program, print the source before and after both approaches. A visible change teaches more than memorising “one returns a list, one returns None” without an example.
CHAPTER 4 OF 20 · Keep records and keys clear
4. Extract a feature while keeping the record
report = sorted(records, key=lambda row: row["books"])
print([row["entry"] for row in report]) # [1, 3, 2]
The lambda receives one record and returns its book count. Python uses that count for comparison, then arranges the original records in the returned list. Arun's name remains connected to Arun's count. There is no need to sort names separately and try to reconnect them later.
For teaching, draw two columns on paper: “record” and “comparison feature.” Write Mina's whole record on the left and 6 on the right. Repeat for the others. Then rearrange the left-hand records according to the right-hand values. This makes the key's role concrete.
The key is a function, not the already-computed result of calling a function on the whole dataset. key=len can order strings by length. key=len(records) supplies an integer where a callable is required. Ask what object will be handed to the key on each visit; that question resolves many apparently mysterious errors.
If lambda feels like a spell, write the key as an ordinary function first.
def book_count(row):
return row["books"]
report = sorted(records, key=book_count)
Both forms express the same small extraction job. The named function can be easier to discuss, test and expand. The lambda can be convenient when the rule is short and obvious. Neither form makes a badly chosen field sensible.
Give the learner one record and ask what book_count(record) should return. If they cannot answer, the obstacle is probably dictionary access or function input and output, rather than sorting. Return to that dependency with one example. There is no benefit in piling tuple keys on top of a shaky extraction rule.
Keep key functions predictable. A key that changes records, reads a changing external counter or depends on unrelated state makes the report harder to reason about. In this exercise, extracting a known field is enough. A simple function with a clear return value is a strength, not a beginner limitation to be hurried past.
report = sorted(records, key=book_count, reverse=True)
print([row["entry"] for row in report]) # [2, 1, 3]
This matches the first brief. The counts descend, and Mina remains before Lena among the equal counts. Say both parts of the rule aloud. “Highest first” is incomplete when the report also has a policy for ties.
Avoid assuming that reverse=True is equivalent to sorting in ascending order and reversing the finished list in every respect. Reversing an ascending result would also reverse the order within equal-key groups. Python's descending sort preserves the relative order of equal keys.
This is an excellent prediction exercise. Ask for the entry sequence using descending sorting, then ask for the sequence obtained by reversing the ascending output from chapter 4. The results are 2, 1, 3 and 2, 3, 1 respectively. A learner who notices the difference has begun thinking about the contract, not just the direction of an arrow.
Stable sorting preserves the source order of records with equal keys. It does not decide whether that source order is the appropriate rule for your task. If the source arrived in an arbitrary order, preserving it may also preserve an arbitrary tie order.
In the reading challenge, original entry order is a deliberate policy. In a different report, the brief might require alphabetical display names after comparing book counts. Those are different requirements. Neither should be silently substituted for the other because the output looks tidy.
Ask the learner to invent two records with the same count and different names. A tie example tests a part of the program that three unequal numbers cannot expose. If the child only tests 3, 5 and 8, every sensible direction rule may appear to work.
This is also a useful conversation about data reports. Order can imply priority even when the underlying numbers are equal. A clear caption such as “Counts descending; ties retain entry order” helps readers understand what the arrangement means. The program's precision should carry through into its presentation.
CHAPTER 8 OF 20 · Set direction and tie rules
8. Build a tuple key for several decisions
Now change the brief: highest count first, then names in a case-insensitive alphabetical order.
report = sorted(
records,
key=lambda row: (-row["books"], row["name"].casefold())
)
print([row["entry"] for row in report]) # [2, 3, 1]
The tuple is compared from left to right. Negating the numeric count makes a larger original count produce a smaller first component. The name component is consulted when counts tie. Lena therefore precedes Mina among the six-book entries.
Have the learner write the three keys: (-6, "mina"), (-9, "arun") and (-6, "lena"). Sorting those small tuples on paper makes the rule inspectable. The records themselves still remain whole.
Do not negate a name to make it descend; strings do not support that numeric operation. Mixed direction sorting needs a deliberate method. For this example, descending numeric count and ascending text are exactly what the tuple expresses. Different instructions require a different key or carefully ordered stable passes.
CHAPTER 9 OF 20 · Handle comparison conditions
9. Use stable passes when directions differ
Suppose a brief asks for counts descending and names descending within ties. Stable passes can make the priority visible.
by_name = sorted(records, key=lambda row: row["name"].casefold(),
reverse=True)
report = sorted(by_name, key=book_count, reverse=True)
print([row["entry"] for row in report]) # [2, 1, 3]
Do the lower-priority ordering first. The final pass establishes the main count groups, while stability preserves the earlier name ordering inside equal-count groups. If you reverse the passes, the final name sort makes names the main priority instead.
This is a good place to slow down. Draw a box around each equal-count group after the second pass. The learner should be able to explain what survives from the first pass and what changes in the second.
A tuple key is often concise, but readable stable passes can be easier for mixed directions. Choose the form the learner can justify with a counterexample. Understanding one well is more valuable than copying several clever forms without knowing which priority they implement.
CHAPTER 10 OF 20 · Handle comparison conditions
10. Separate text ordering from human expectations
names = ["zoe", "Arun", "lena"]
print(sorted(names)) # ['Arun', 'lena', 'zoe']
print(sorted(names, key=str.casefold))
Use a stronger contrast to expose the issue: ['Zoe', 'arun'] sorts differently with and without a casefold key. Raw string comparison follows character ordering; it does not automatically apply every human naming convention.
casefold() helps remove case distinctions for comparison. It does not turn a list of names into a culturally complete directory. Accents, different scripts and locale-specific conventions need requirements of their own. Preserve the original display name instead of replacing every name with the folded key.
For this fictional report, state the modest contract: compare casefolded strings, retaining source order when those keys tie. That is accurate and teachable. Avoid promising “perfect alphabetical order for all Singapore names.” A small classroom example should not conceal the limits of its comparison rule.
CHAPTER 11 OF 20 · Handle comparison conditions
11. Treat numbers stored as text carefully
text_counts = ["9", "12", "3"]
print(sorted(text_counts)) # ['12', '3', '9']
print(sorted(text_counts, key=int)) # ['3', '9', '12']
The second output still contains strings. Conversion inside the key changes comparison values, not the original items. This is another chance to check the distinction from chapter 4.
But int will fail on text such as "unknown". Do not build a hidden rule that treats every invalid value as zero merely to keep sorting running. Zero can be a valid count, and “not supplied” is different information.
For a report with real input, decide where validation belongs. A clear approach is to parse and validate the records before creating the ordered view. The sorting stage then works with a known type. When the learner sees a ValueError, ask which input broke the parsing contract. The problem may be the data, not the sort's order.
CHAPTER 12 OF 20 · Handle comparison conditions
12. Give missing values a visible policy
Suppose an optional count can be None. The report requires known counts descending, then unknown counts, preserving source order among unknowns.
def report_key(row):
count = row["books"]
return (count is None, 0 if count is None else -count)
sample = [{"books": None}, {"books": 0}, {"books": 5}]
print([r["books"] for r in sorted(sample, key=report_key)])
# [5, 0, None]
The first component puts known counts before missing ones. The second component orders known counts. Its zero for missing records is only a comparison placeholder inside their separate group; it does not replace the missing value in the record.
This rule assumes each record has a books key and that non-missing values are valid comparable numbers. A missing dictionary key is a different case. Validate that structure rather than quietly introducing several kinds of absence into one expression.
Ask the learner to explain where zero belongs. If they place it with unknowns, they have confused absence with a legitimate value. That is a data-model issue worth repairing before further Python practice.
For this teaching task, accept a non-empty string name and a non-negative integer count. We can exclude booleans explicitly because Python treats bool as a subclass of int.
def valid_record(row):
return (
isinstance(row, dict)
and isinstance(row.get("name"), str)
and bool(row["name"].strip())
and type(row.get("books")) is int
and row["books"] >= 0
)
This function describes our fictional input contract, not a universal validation system. It does not check entry-number uniqueness or every possible name convention. Say what it checks and keep the next stage within that boundary.
Reject or report invalid records before sorting; do not quietly remove them and present the remaining report as complete. A learner can return a list of rejected entry numbers for review. That keeps the evidence visible.
In a family lesson, use invented records. Real names, school marks and private class lists are unnecessary for mastering a comparison rule. Three carefully chosen fake rows can reveal a problem more clearly than a large personal spreadsheet.
Two participants can have the same display name and count. A report should still distinguish their records through a suitable identifier. In our exercise, entry provides that identifier.
Do not use a display name as proof that two records are the same. If a child sorts one list of names and another list of counts separately, matching by repeated names afterwards can misattach values. Keeping complete records together prevents that particular error.
An explicit identifier can also supply a deterministic final tie rule, such as (-books, folded_name, entry). That changes the contract from “preserve source order for complete ties” to “compare entry numbers for complete ties.” State which one the task needs.
This is a useful transfer question: if the source rows are rearranged before running the program, should the final report change? Under source-order ties, it can. Under a complete explicit key, it should not change for records with unique identifiers and the same data. The requirement decides which behaviour is correct.
CHAPTER 15 OF 20 · Validate and test
15. Inspect a generator before relying on it twice
sorted() accepts an iterable and collects its items into a list. If that iterable is a generator, producing the sorted result consumes it.
source = (n for n in [6, 9, 6])
report = sorted(source)
print(report) # [6, 6, 9]
print(list(source)) # []
A child who expects the generator to behave like a reusable list may blame sorting for “losing” data. The actual issue is the one-pass source. If both original order and a sorted view are required, materialise the input intentionally before sorting it.
This connects naturally with the Python zip lesson. Use that guide when the learner needs to understand iterable consumption, then return here with a clear account of what the source can supply.
Do not introduce generator complexity before a learner can sort three ordinary records. It is a later boundary case, useful precisely because the simple model is already secure.
A useful test checks more than whether a result exists. For the first brief, verify descending counts, preserved identifiers and original order inside equal-count groups.
report = sorted(records, key=book_count, reverse=True)
assert [r["entry"] for r in report] == [2, 1, 3]
assert [r["entry"] for r in records] == [1, 2, 3]
These small expected sequences are independent of the implementation. Writing another sort inside the test and comparing the two can simply repeat the same mistaken rule.
Try an empty list, one record, equal counts, zero counts and mixed capitalisation. If the contract permits missing values, test those too. If the contract rejects them, check that rejection rather than pretending they are valid report entries.
Let the learner break a rule deliberately. Remove reverse=True; change the tuple order; sort the count strings without conversion. Each change should make a chosen check fail. A test that never notices a relevant mistake is a weak guide, however neatly it is written.
Use these fictional rows: Noor has 4 books and entry 1; Ben has 7 and entry 2; Ava has 7 and entry 3; Kai has 0 and entry 4. First predict the entry sequence for counts descending with source-order ties. Then predict it for counts descending with ascending casefolded names.
The answers are 2, 3, 1, 4 and 3, 2, 1, 4. The difference occurs only inside the seven-book group. Explain that difference before writing either key.
Next, ask for names ascending as the main rule and counts descending only when names tie. Many learners reuse the previous key because it contains the correct ingredients. But priority matters: a tuple beginning with count does not become a name-first report merely because a name appears later.
Add two records named Ava and ava with different counts. This exposes the second priority after casefolding. A good exercise changes the reasoning demand, not just the numbers in a copied template.
If the result is None, inspect whether an in-place operation was assigned to a variable. If names and counts become disconnected, inspect whether complete records stayed together. If ties behave unexpectedly, write the full tie contract and inspect the source order. If a value cannot be compared, inspect input types.
Do not respond to every error with another long worksheet. One carefully chosen counterexample can identify the missing connection. A learner who cannot evaluate row["books"] needs dictionary practice; a learner who can extract the count but prioritises the wrong tuple component needs comparison practice.
The eduKate diagnostics and recovery hub provides a wider route for locating a learning bottleneck. Bring the actual small example and the learner's explanation. Return with the earliest repair, rather than an unsupported label such as “not a coding person.”
The hopeful part is that these errors are specific. Once the underlying distinction becomes visible, the next report is usually much easier to discuss and check.
Ask, “What does your key return for this one record?” Then ask, “What happens when these two keys are equal?” Finally ask, “Which original information is still attached to each row?” Those three questions reveal more than whether the child can recite the name sorted.
For a busy Punggol evening, choose one brief and one changed condition. Keep the record set small enough to predict on paper. The next session can begin with a new tie example, without showing the previous solution immediately.
If you are discussing coding support with a tutor, ask for a demonstration matched to the learner's current knowledge and clarify whether computing enrichment is actually available. This article supplies a lesson, not a timetable or course promise. A suitable teacher should be able to explain the input contract, model a comparison and let the child repair a meaningful mistake.
Progress is the learner being able to justify a report under a changed rule. A prettier printout is pleasant, but independent reasoning is the more useful result.
CHAPTER 20 OF 20 · Practise and explain
20. Keep the comparison contract beside the program
Finish the report with a short note: accepted record types, main ordering field, direction, tie rule and treatment of missing values. That note lets another person understand the output without guessing from its appearance.
For the original reading challenge, the contract is compact: validated fictional records; book counts descending; equal counts retain entry order; source order remains available through a separate list. The program and the report caption should agree with that statement.
Continue with the Python enumerate lesson when you need display numbers. A displayed rank or row number is separate from the stored entry identifier; sorting should not silently rewrite identity.
Technical references: Python's Sorting HOW TO, built-in sorted documentation, list methods and operator itemgetter. These provide the language rules; the fictional report and prediction exercises above show how to apply them.

