← Practical Python
02 / 10 · 23 MIN

Collections without surprises

Choose lists, sets, and dictionaries for the problem at hand.

Structure is part of the solution

A list maintains a sequence and permits duplicates. A set represents unique values and supports membership tests. A dictionary maps keys to values. Choose a structure from the meaning of the data rather than the shortest syntax.

Sharing and copying

Assigning b = a does not copy a list: both names refer to the same object. A shallow copy creates a new list, but nested mutable objects may still be shared. Before modifying a structure, understand who else depends on it.

Guided workplace application

An importer needs to count unique IDs and retain original order for audit. Use a set for membership when order does not matter, but retain the sequence if the contract requires it. Do not assume sorting removes duplicates. When passing a list to a function, assignment shares the object; append may be visible to the caller. A shallow copy separates the outer list but leaves inner lists or dictionaries shared. Decide whether you want mutation, a shallow copy, or reconstruction of the needed fields. Also check method return values: ids.sort modifies ids and returns None; sorted(ids) returns a new list. This distinction explains many unexpected results without blaming concurrency or the data source.

Duplicates before constructing a mapping

A dict created from repeated pairs retains only one value per key. If rows should have unique IDs, check repetition while the list or stream still retains every occurrence. Counting keys in the final mapping does not recover replaced rows. Define rejection, reconciliation, or update according to the contract; the constructor choice should not silently decide business policy.

Preserve order and multiplicity

List sorting is stable: items with the same key retain relative input order. It does not automatically add another business criterion. In reconciliation, distinguish presence from frequency. set removes repetition, whereas Counter built from hashable IDs retains how often each appeared. Two lists with the same length and set may have different per-ID counts. Choose the representation according to the information the contract must preserve.

owners = {"batch": "ops", "report": "data"}
team = owners.get("api", "unassigned")
unique_ids = set([101, 101, 102])
IN PRACTICE

You need to count unique files received each day. A set removes duplicates but does not retain arrival order as a sequence. If order matters, retain the original sequence as well.

Common pitfalls

Assuming assignment copies; overlooking shared inner objects; assigning sort’s return.

Related topics: Small functions, clear contracts · Errors and files with context

Take this idea with you

Assignment shares references. Choose the collection and copy depth deliberately.

Create account

Reference: Python 3.14: Shallow and deep copying · Python 3.14; DR Python 2026.3