Python: lesson 7 of 7
Python
Lists, Tuples, Sets, and Dictionaries
Choose the right Python collection for features, dimensions, categories, and model metrics.
Concept
Collections store multiple values. Python's four everyday collections have different strengths: lists preserve an editable order, tuples preserve an ordered fixed grouping, sets keep unique values, and dictionaries connect keys to values.
Why It Matters
Data Science code uses collections constantly: a list of feature names, a tuple containing dataset dimensions, a set of unique categories, or a dictionary of model metrics. Choosing the collection that matches the meaning makes code simpler and prevents mistakes.
Intuition
Use a list for a changeable checklist, a tuple for a fixed pair or record shape, a set for a bag of unique labels, and a dictionary for a labeled lookup table.
Lists
Lists are ordered and mutable. Indexing starts at zero; slices select a range without including the final position.
feature_names = ["age", "tenure", "monthly_charge"]
print(feature_names[0])
print(feature_names[1:])
feature_names.append("support_calls")
feature_names.remove("tenure")
print(len(feature_names))
Expected output:
age
['tenure', 'monthly_charge']
3
The final list is ['age', 'monthly_charge', 'support_calls']. Use a list when order matters and you expect to add or remove items.
Transformation Versus In-Place Mutation
Because lists are mutable, it matters whether you create a new result or change the original object.
prices = [100, 200, 300]
taxed_prices = [round(price * 1.1, 2) for price in prices]
print(prices)
print(taxed_prices)
Expected output:
[100, 200, 300]
[110.0, 220.0, 330.0]
This transformation returns a new list and leaves prices unchanged. In contrast, list methods such as append and remove, or assigning prices[index] = value, mutate the existing list. Mutation is useful when intended; the important question is whether callers expect the original object to change.
Tuples
Tuples are ordered but immutable: their contents cannot be changed after creation.
dataset_shape = (1500, 24)
row_count, column_count = dataset_shape
print(row_count, column_count)
Expected output: 1500 24. A tuple is useful for a fixed grouping such as dimensions or a coordinate. Its immutability signals that the grouping should not be edited in place.
Sets
Sets keep unique values and support fast membership checks. They do not preserve a dependable display order.
observed_categories = {"basic", "premium", "basic", "enterprise"}
print(observed_categories)
print("premium" in observed_categories)
The printed ordering may vary, but duplicates are removed and the membership check returns True. Sets are useful for unique categories and checking whether a feature has already been seen.
Dictionaries
Dictionaries store key/value pairs. Use a key to retrieve, add, or update a related value.
model_metrics = {
"accuracy": 0.91,
"precision": 0.84,
"recall": 0.78,
}
print(model_metrics["precision"])
model_metrics["f1_score"] = 0.81
model_metrics["accuracy"] = 0.92
Expected output: 0.84. The keys communicate what each metric means, which is safer than relying on positions in a list.
Shared-Reference Behavior
Two names can point to the same mutable object.
metrics = {"accuracy": 0.91, "precision": 0.84}
alias = metrics
alias["precision"] = 0.50
print(metrics)
Expected output: {'accuracy': 0.91, 'precision': 0.5}. Updating alias also changes metrics because they refer to the same dictionary. The same idea applies when a list or dictionary is passed into a function.
Real-World / Data Science Example
An analysis may need each collection type for a different reason.
feature_names = ["age", "income", "tenure"]
train_shape = (10000, 3)
unique_regions = {"north", "south", "north"}
metrics = {"precision": 0.86, "recall": 0.79}
print(feature_names)
print(train_shape)
print(unique_regions)
print(metrics["precision"])
The collection choice documents the data's meaning: editable feature order, fixed shape, unique labels, and named scores.
Explanation of the Code
List methods such as append and remove change a list. Dictionary assignment changes a dictionary in place. Tuple unpacking assigns each position to a name. Set literals use braces but contain values only; dictionary literals also use braces but contain key: value pairs. Access a dictionary value with square brackets and its key.
When to Use It
Use lists for ordered, editable items; tuples for fixed grouped values; sets for uniqueness and membership; dictionaries for named attributes or summaries. Do not select a type just because it can hold the values: select it because its behavior matches the job.
Failure Signals
Common Mistakes
- Expecting a set to keep insertion order for analysis output.
- Trying to change a tuple element.
- Accessing a missing dictionary key without handling it.
- Mutating a list while iterating through it.
- Confusing
{1, 2}(a set) with{"a": 1}(a dictionary). - Forgetting that updating a list or dictionary can affect other code that shares the same object.
Best Practices
Use descriptive dictionary keys and avoid relying on numeric positions for important metrics. Use .get("key") when a dictionary key may be absent. Convert a set to a sorted list before presenting it to a user when stable order matters. When working with a mutable collection, be clear whether you are intentionally modifying it or returning a transformed copy.
Data Science Perspective
These collections prepare you for later tools. Feature-name lists become DataFrame columns, tuples appear in array shapes, sets help inspect unique categories, and dictionaries hold configurations, metric reports, and mappings for categorical values.
Interview Perspective
Question: When would you choose a set over a list? A strong answer: when uniqueness or frequent membership checking matters and order is not the main requirement.
Worked Example: Safely Read a Metric Summary
Use .get() when a metric may not be present in every evaluation run.
metrics = {"accuracy": 0.90, "precision": 0.82}
recall = metrics.get("recall")
if recall is None:
print("Recall was not reported")
else:
print(recall)
Expected output: Recall was not reported. This avoids a KeyError while making the missing metric explicit.
Practice Questions
- Create a list of three feature names and append a fourth.
- Store
(rows, columns)for a dataset and unpack it into two names. - Explain the difference between returning a transformed list and mutating the original list in place.
- Create a dictionary for accuracy, precision, and recall, then update recall.
Quick Quiz
- Which collection is immutable: list or tuple? Answer: tuple.
- Which collection removes duplicates: set or dictionary? Answer: set.
- Which collection types in this lesson are mutable? Answer: lists and dictionaries.
- How do you access accuracy in
metrics? Answer:metrics["accuracy"].
Key Takeaway
Key Takeaways
Lists, tuples, sets, and dictionaries store multiple values with different guarantees. Match the collection to whether you need order, mutability, uniqueness, or named lookup, and be deliberate about whether mutable collections are transformed or changed in place.
Next Lesson
You now have the Python foundations needed to begin working with numerical arrays and tabular data.
Finish this lesson on your terms
Mark it complete when you have worked through the material and are ready to move on.