03 / REUSABLE LOGIC · LESSON 10

Select, transform, and sort

Build a predictable report from a list of records.

13 min · learn at your pace

A list built from another collection

A list comprehension combines a transformation, a source, and an optional condition: [name.upper() for name in names if name]. Read it as “uppercase each nonempty name.” It creates a new list and leaves the source collection in place.

A comprehension is useful when it stays small. If you need several branches, error handling, or side effects, a normal loop is often easier to follow. Shorter code is not automatically clearer code.

Sort by an explicit field

sorted(records, key=lambda row: row["name"]) returns a new sorted list. The small lambda function tells Python which value to compare. Later you will write named functions for larger jobs. records.sort() changes the existing list and returns None.

Filter on numeric values before turning them into strings. Sorting numeric-looking text orders characters, which can put "100" before "20". A stable, explicit report order makes differences between runs easier to review. Here we sort by hostname after selecting active servers that meet a memory threshold.

Try an example.py
names = ["web-02", "db-01", "app-01"]
upper_names = [name.upper() for name in names]
print(sorted(upper_names))
YOUR TURN

Put it into practice.

From the supplied servers list, create eligible as a list of active records with at least 16 GB RAM, sorted by name ascending. Create names as their names in the same order. Keep servers unchanged.

See an explained solution
One way to solve it.py
servers = [
    {"name": "web-02", "active": True, "memory_gb": 8},
    {"name": "db-01", "active": True, "memory_gb": 32},
    {"name": "old-01", "active": False, "memory_gb": 64},
    {"name": "app-01", "active": True, "memory_gb": 16},
]
eligible = sorted([row for row in servers if row["active"] and row["memory_gb"] >= 16], key=lambda row: row["name"])
names = [row["name"] for row in eligible]
print(names)

The filter retains app-01 at exactly 16 GB and db-01 at 32 GB. sorted returns a new list; the original inventory order stays available.