Typorithm · medium

Comprehensions, filtering and stable sorting

pythonscriptingdata-boundariesindependent-practice
Saved on this device
Full lesson · 4 learning steps Open any exercise for focused practice
1

Step 1 of 4 · intro card

Comprehensions, filtering and stable sorting

0%

Concept and contract

Express one clear transformation without hiding the population rule or mutating the source.

A comprehension can express a small selection and projection clearly after its loop behavior is understood. The worked function selects active rows in the requested country, projects their identities and returns a newly sorted list. The input rows are already validated records with string identities under this lesson's contract.

The two eligibility conditions combine with and. An archived row in the chosen country and an active row in another country are both excluded. The fixture deliberately contains both so a superficially plausible or predicate cannot pass by checking only that some result exists.

Mechanism and worked example

The generator expression supplies selected identities to sorted, which materializes the final list in the requested ascending order.

The generator expression supplies selected identities to sorted, which materializes the final list in the requested ascending order. This is not a promise that the complete operation has constant memory: the sorted output must be built. The input collection itself remains unchanged.

Write an equivalent explicit loop when learning the expression. Read its for part, its if condition and its projected value separately. A comprehension should make that simple flow easier to review rather than compress unrelated validation, side effects and error recovery into one dense line.

Complete worked example

python

def select_ids(rows, country):
    return sorted(row["id"] for row in rows
                  if row["active"] and row["country"] == country)
Reasoning
The expression filters with both conditions before sorting selected identities.

Counterexamples and common mistakes

The counterexample replaces and with or and admits both negative cases.

The counterexample replaces and with or and admits both negative cases. Another common mistake calls rows.sort and returns its None result, or sorts caller-owned data in place without documenting the mutation. Correct membership, output order and input preservation are independent properties.

Avoid constructing a set merely to hide duplicate observations unless uniqueness is the actual business contract. This input assumes distinct role identities; a later capstone checks identity conflicts explicitly. Concise syntax must not silently choose an entity-merging policy.

Counterexample: a plausible but incorrect implementation

python

def select_ids(rows, country):
    return sorted(row["id"] for row in rows
                  if row["active"] or row["country"] == country)
Reasoning
OR admits inactive local rows and active foreign rows.

Independent practice: small Python task

Keep the same active-country eligibility rule but return identities in descending order.

Keep the same active-country eligibility rule but return identities in descending order. The small independent change concerns presentation only. Predict r2 before r1 when both are eligible, while excluding any inactive or foreign-country record just as before.

Use the reverse option on sorted rather than modifying the source list or reversing the filter conditions. First mark the eligible identities by hand, then choose their output order. That separation prevents a sorting adjustment from masking a membership error.

Step 1: Keep the same two eligibility predicates. Step 2: Set the output sort direction to descending.

Practice starter: solve before reading the solution

python

def select_ids(rows, country):
    # Keep eligibility and return identities in descending order.
    raise NotImplementedError
Reasoning
Change the sorted output direction while keeping membership intact.
  • Hint 1: Use sorted with reverse=True.
  • Hint 2: Do not alter source rows or remove one condition.

Solution, tests and trade-offs

The solution uses the same comprehension and sorts the selected identities with reverse=True.

The solution uses the same comprehension and sorts the selected identities with reverse=True. It returns a fresh list and preserves source records. Empty and no-match populations return an empty list, a consistent shape rather than None or a fabricated placeholder identity.

Acceptance compares exact ordered identities and the untouched input. A result count of two would not prove the right two rows were chosen, and a correct set would not prove the requested descending presentation. The core task deliberately tests all three properties without adding a new data model.

Practice solution and acceptance checks

python

def select_ids(rows, country):
    return sorted((row["id"] for row in rows
                   if row["active"] and row["country"] == country), reverse=True)
Reasoning
The reversed presentation does not change the input or eligible identity set.

Interview reasoning and next step

In an interview, explain the equivalent loop and the materialization boundary before discussing a comprehension's brevity.

In an interview, explain the equivalent loop and the materialization boundary before discussing a comprehension's brevity. Give a case where a named helper or normal loop is clearer. Readability and an explicit contract are more useful than choosing the shortest expression in every situation.

The next lesson introduces a parser that accepts a broader external representation and reports invalid values. That boundary belongs before this already-validated transformation rather than being hidden inside every selection expression.

Optional stretch — after the core task works: Rewrite the worked expression as an explicit loop and compare outputs on the two negative fixture rows.

Computer practice: https://applydjinn.com/typorithm/python-lab-20261105.zip. Run verify.py with your selected Python interpreter, then complete an exercise and check it with --practice followed by the lesson id. The lab uses only the standard library and disposable local fixtures; it never connects to the production database or company feeds.

Express one clear transformation without hiding the population rule or mutating the source.