Sub topic 10
A decision guide for choosing a collection
This chapter assumes you know how lists, tuples, dicts, and sets behave, and what hashability means. It turns that knowledge into a repeatable way to choose. You will ask a few questions about your data, then check the choice against cost and pitfalls.
Start with what the data is
Most choices become clear once you answer five questions about the data, in this order:
- Do you look values up by a name or key, rather than by position? Use a dict.
- Do you only care whether something is present, or need uniqueness? Use a set.
- Does position matter, and will the contents change? Use a list.
- Is it a fixed record, or does it need to be a dict key or set element? Use a tuple.
- If none of these fit, check the standard library alternatives at the end of this chapter.
The flow is a starting point. Real data often needs a combination, such as a list of tuples or a dict of lists.
What each question costs and gives you
| Need | Best fit | Why |
|---|---|---|
| Order, duplicates, growth | list | Indexable, mutable, allows repeats |
| Fixed record, hashable composite | tuple | Immutable, can be a dict key |
| Key to value lookup | dict | Average constant-time lookup by key |
| Unique items, membership, set algebra | set | Average constant-time `in`, union, intersection |
Membership testing is where the choice matters most for speed. Testing x in some_list scans the list, so its cost grows with the list length. Testing x in some_set or x in some_dict hashes the value and jumps to it, which is constant time on average. If you run many membership tests against the same data, convert it once to a set.
Order is no longer a reason to avoid dicts. Since Python 3.7, dicts keep insertion order. Sets do not guarantee any order, so use sorted when you print them.
A worked example
Suppose you have a log of orders, each a (customer, item) pair. The log itself is a list, because order matters and new orders arrive. Each order is a tuple, because it is a fixed record.
orders = [("ana", "tea"), ("ben", "tea"), ("ana", "milk"), ("cy", "tea")]
# dict: count orders per customer
counts = {}
for customer, item in orders:
counts[customer] = counts.get(customer, 0) + 1
print(counts) # {'ana': 2, 'ben': 1, 'cy': 1}
# set: unique customers, then set algebra against another group
customers = {c for c, _ in orders}
vip = {"ana", "cy"}
print(sorted(customers)) # ['ana', 'ben', 'cy']
print(sorted(customers & vip)) # ['ana', 'cy']
# dict of lists: group customers by item
by_item = {}
for customer, item in orders:
by_item.setdefault(item, []).append(customer)
print(by_item) # {'tea': ['ana', 'ben', 'cy'], 'milk': ['ana']}Each structure matches one job:
- The list keeps arrival order.
- The tuples keep each order together.
- The dict answers "how many for this customer?" without scanning.
- The set answers "who is in both groups?" in one expression.
Combining collections
Nested structures are common, and the same questions apply at each level.
- List of tuples: many fixed records in order, such as rows from a file.
- Dict of lists: one key mapping to many values, such as items grouped by category.
- Dict of sets: one key mapping to many unique values, such as tags per article.
- Set of tuples: unique composite items, such as visited
(x, y)grid cells.
The last case works because tuples of numbers are hashable. A set of lists would raise TypeError.
Checks before you commit
Run through these before settling on a choice:
- Hashability: Dict keys and set elements must be hashable. If your key is a list, convert it to a tuple. If it is a set, convert it to a
frozenset. - Duplicates: If duplicates carry meaning, such as repeated purchases, a set will silently discard them. Use a list or count them in a dict.
- Mutation: If several parts of your program hold the same list, a change in one place shows up everywhere. Copy it, or use a tuple when nothing should change.
- Defaults: Never use a list or dict as a default argument value. Use
Noneand create the object inside the function.
When the basics are not enough
The standard library has specialized types for common patterns. Use them when your code repeats a workaround:
collections.namedtuplegives tuple fields readable names.collections.Counterreplaces the manual counting loop above.collections.defaultdictreplaces thesetdefaultgrouping pattern.collections.dequesupports fast appends and pops at both ends, where a list is slow at the front.frozensetis an immutable set that can serve as a key.
Exercise
You have 100,000 product IDs in a list and must test whether each of 1,000,000 incoming IDs is known. Which collection should you convert the list to, and why?
Show answer
A set. Each in test on a list scans it, so the total work grows with both sizes. A set hashes the ID and checks it in constant time on average, so each test stays cheap. Duplicates and order do not matter for this task, so nothing is lost.
Exercise
You need to store the number of times each word appears in a text, and later print the words in the order they first appeared. Which collection fits, and does it keep that order?
Show answer
A dict mapping word to count. Dicts preserve insertion order, so words print in first-seen order. A set could not hold counts, and a list would need a scan to find each word.