Lists and dictionaries for samples
Quick answer
A list keeps samples in order. A dictionary associates field names with values for one sample. Together they form a readable representation of a small table. For a parcel task, each row has an identifier, dispatch distance, and observed duration in minutes. Keep the identifier for tracing results, and use the outcome only where the learning or evaluation step requires it.
Extract a feature and target separately
A list comprehension has the form [expression for item in items]. It constructs a new list. Access named dictionary fields to avoid confusing the order of columns. Here duration is a later observation, not an input available at dispatch.
rows = [{"id": "p1", "km": 3, "minutes": 11}, {"id": "p2", "km": 5, "minutes": 15}]features = [row["km"] for row in rows]targets = [row["minutes"] for row in rows]print(features)print(targets)Expected output:
[3, 5][11, 15]Both lists preserve the row order. Index 0 in each refers to p1. Do not sort or filter either list independently.
Iterate once or make a new iterator
An iterator supplies elements one at a time. iter creates an iterator over a list; next consumes one element. A comprehension over the same iterator receives the remaining elements only.
distances = [3, 5, 7]stream = iter(distances)print(next(stream))print([value for value in stream])print(list(stream))print(distances)Expected output:
3[5, 7][][3, 5, 7]The iterator is exhausted after the comprehension, but the original list is unchanged. For another pass, iterate over the list again. For large streams, deliberately design one-pass calculations instead of assuming everything fits in memory.
Common mistakes
A missing dictionary key is not zero. Treat missing values as an explicit data-quality issue, not an invented measurement. Also, a new list of existing dictionaries does not copy those dictionaries; editing a shared record can change the source. Build new records or extract scalar values when needed.
Practice and next steps
Create a third row, extract its ID, distance and target in matching order, and predict how many values remain after calling next twice. Do not include the observed duration as a dispatch feature.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Lists and dictionaries for samples — knowledge check
Apply the lesson to small reproducible experiment scenarios.
What represents one parcel in the lesson?
Which dispatch feature avoids using the later outcome?
What happens if you sort only the targets?
After consuming all items of a list iterator, what remains in that iterator?
What is an appropriate response to a missing distance key?