Beginner 13 min

Lists and dictionaries

Choose between position-based access and lookup by key.

Use a list for a sequence

A list preserves items in order and allows repeated values. Its index starts at zero. Append to the end with append, or iterate directly over values when you do not need their positions.

How it works

Imagine a list of book titles and a dictionary of titles by ID. The list is useful when order matters and you intend to read through each item. The dictionary lets a caller ask about a specific ID. Decide what happens for a missing key before relying on a lookup.

Use a dictionary for lookup

A dictionary associates unique keys with values. In a frequency counter, use each word as a key and its count as the value. counts.get(word, 0) supplies a zero for a word you have not seen yet.

Code example

words = ["fern", "moss", "fern"]
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts["fern"])

Check your understanding

Count the occurrences of moss in each list.

See the example and explanation
Example 1
Given ["moss", "fern", "moss"]
Answer 2
Example 2
Given ["fern"]
Answer 0

Use counts.get("moss", 0) to read the result so an input without moss produces zero.

Open practice problem
Next lessonFunctions and return values