Before this lesson
Understand Python conditions, loops and indexing. This lesson distinguishes sequences, mappings and sets.
What you will be able to do
Choose containers, understand shared references and filter or sort records predictably.
Understand the mechanism
Lists model ordered sequences, dictionaries mappings and sets membership. Use records inside a list and a set for completed IDs when those relations fit the task.
Missing-key access raises KeyError, while get can supply a deliberate default. Missing duration should not automatically become zero and hide faulty data. Membership tests differ by container.
Lists and dictionaries are mutable. Copying an outer list leaves nested records shared; editing a record can affect both lists. Copy records deliberately and understand deeper nesting before choosing deep copying.
sorted returns a new list whereas sort mutates and returns None. A key selects the comparison basis. Sets should not define presentation order; sort explicitly when order matters.
Runnable example
Use Python 3.11 or later. Save lesson.py in a separate practice directory and run python3 lesson.py, or py lesson.py on Windows. Examples use only the standard library.
courses = [{"id": 1, "title": "Python", "minutes": 30},
{"id": 2, "title": "SQL", "minutes": 20},
{"id": 3, "title": "Java", "minutes": 40}]
done = {1, 1, 3}
pending = [item for item in courses if item["id"] not in done]
ordered = sorted(courses, key=lambda item: item["minutes"])
print([item["title"] for item in pending])
print([item["id"] for item in ordered])
print([item["id"] for item in courses])
print(len(done))
Trace and verify
Only SQL is pending; sorted IDs are 2, 1, 3 while the source remains 1, 2, 3. The set has two members. Compare in-place sorting, then restore the original state.
Common mistakes and boundaries
Titles are not stable identity. Comprehensions suit readable transformations rather than deeply nested side effects or exception handling.
Practice challenge
Build an ID lookup, handle missing records, and total pending duration.
Reference solution and reasoning
Build the mapping only after checking unique IDs because duplicate keys overwrite. Sum valid pending durations, with zero for an empty selection.