01.04 Lesson 4 of 10
36 minCollections & Comprehensions
Choose lists, tuples, sets and dictionaries based on how the data is used.
By the end of this lesson
You will be able to
- Use a list for ordered mutable sequences.
- Use a dictionary for key-value lookup.
- Use a set for uniqueness and membership checks.
- Write a simple list or dictionary comprehension.
Use the collection that matches the operation
Lists preserve order and can be changed. Tuples are fixed sequences. Sets contain unique values and support membership and set operations. Dictionaries map unique keys to values.
columns = ["hour", "temperature", "count"]
point = (8, 0.42, 120)
unique_hours = {8, 9, 10}
record = {"hour": 8, "count": 120}
print(record["count"])
print(9 in unique_hours) Comprehensions create a transformed collection
A comprehension is useful when the transformation is short and readable. Keep multi-step logic in a normal loop or function instead of compressing it into one expression.
counts = [12, 18, 25, 19]
large_counts = [value for value in counts if value >= 18]
labels = ["hour", "temperature", "count"]
positions = {name: index for index, name in enumerate(labels)} Apply what you learned
ExerciseRepresent a dataset row
Model one hourly bike record and create quick summaries from a collection of records.
- Represent a row as a dictionary.
- Store several rows in a list.
- Build a set of distinct hour values.
- Create a dictionary mapping each column name to its position.
- Use a list comprehension to select counts above a threshold.
The structure is readable and each collection is chosen for a clear reason.
Free references
Study resources
- 01
- 02 Lists, Tuples, and Sets Video
Watch this focused lesson; use the docs for dictionaries and comprehensions.
Check your understanding
Self-test
-
Question 1
Which structure is best for checking whether a category has appeared before?
A set, because it stores unique values and supports direct membership tests. -
Question 2
Why is a dictionary useful for representing a row?
Each value is accessed by a meaningful column name rather than a positional index.
Completion check
Move on when
You can represent one row, many rows, unique categories and column positions without mixing their roles.