androidengineers.Book a session

Python 04 · Iteration and transformations

Comprehensions, sorting, and grouping

articleSelf-paced

Learn the concept

Comprehensions express a transformation with optional filtering. They are useful for short, direct operations. When validation and error handling become complex, an ordinary loop is easier to inspect. A comprehension should not hide side effects.

sorted returns a new list; a list’s sort method changes that list. A key function determines the value used for comparison. Python’s sort is stable, so equal keys retain their prior relative order. Use a secondary key when you need a reproducible ordering independent of input order.

Grouping requires choosing the key that matches the question. Grouping tickets by category answers a different question from grouping by customer. Missing categories need an explicit policy. Do not drop them silently and then report an apparently complete aggregate.

Run and inspect

rows = [{"id": "b", "score": 2}, {"id": "a", "score": 2}, {"id": "c", "score": 1}]
ranked = sorted(rows, key=lambda row: (-row["score"], row["id"]))
assert [row["id"] for row in ranked] == ["a", "b", "c"]
assert [n * n for n in range(4) if n % 2 == 0] == [0, 4]

Your exercise

Filter resolved tickets, sort the rest by priority and ID, and count the remaining tickets per category.

Check your understanding

The ordering is deterministic, the input list remains unchanged, and missing categories have an explicit bucket or validation error.

YOUR LEARNING JOURNEY

0 of 42 available lessons completed

Progress saved in this browser. No account needed.
Comprehensions, sorting, and grouping | Python for AI Engineering | Android Engineers