PYTHON / CHAPTER 08
Lists, sets, and dictionaries
IntermediateSelect a collection from its required behavior.
By the end of this chapter
- Use comprehensions for clear transformations
- Preserve order during deduplication
- Distinguish copies from shared nested values
The idea
Lists represent ordered sequences, sets support membership without promising a useful iteration order, and dictionaries associate keys with values while preserving insertion order. Choose the structure from the result you need. A comprehension expresses a transformation and optional filter; an explicit loop is often clearer when several branches or multiple accumulating results are involved.
Assignment creates another reference rather than copying a collection. A shallow copy creates a new outer list or dictionary but still shares nested objects. Preserve caller-owned data by constructing replacements at every level you change. When removing duplicates while retaining order, combine a set for membership with a list for output instead of relying on set iteration. Include repeated values and empty input in your examples.
seen = set()
unique = []
for label in ["api", "ui", "api"]:
if label not in seen:
seen.add(label)
unique.append(label)
print(unique)['api', 'ui']
The set answers membership questions while the output list records first occurrence order. Neither collection changes the source list.
Try it yourself
Group record IDs by status using a dictionary of lists, preserving record order within each status.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
Open Python coding challengesCHECK YOUR UNDERSTANDING