7 stages2 sections22 units

01.04 Lesson 4 of 10

36 min

Collections & 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

Exercise

Represent a dataset row

Model one hourly bike record and create quick summaries from a collection of records.

  1. Represent a row as a dictionary.
  2. Store several rows in a list.
  3. Build a set of distinct hour values.
  4. Create a dictionary mapping each column name to its position.
  5. Use a list comprehension to select counts above a threshold.
Done when

The structure is readable and each collection is chosen for a clear reason.

Free references

Study resources

2 links
  1. 01
    Data structures Article

    Read the list, tuple, set, dictionary and looping-technique sections.

  2. 02
    Lists, Tuples, and Sets Video

    Watch this focused lesson; use the docs for dictionaries and comprehensions.

Check your understanding

Self-test

2 questions
  1. Question 1

    Which structure is best for checking whether a category has appeared before?

  2. Question 2

    Why is a dictionary useful for representing a row?

Completion check

Move on when

You can represent one row, many rows, unique categories and column positions without mixing their roles.

Quick find

Search Michi

Type to search every stage, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels