Pick the shape for the job.
Choose between indexed access, scanning, and building a membership structure.
01 The idea
Python lists behave like dynamic arrays of references: indexed access is constant time, appending is amortised constant time, and inserting at the front shifts existing references. Sets and dictionaries use hash tables to support expected constant-time membership or key lookup. Choose based on operations and semantics, not the collection with the fanciest name.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
tasks = ["Build", "Test", "Review", "Build"]
lookup = set(tasks)
print(tasks[1])
print("Review" in lookup)
print(len(tasks), len(lookup))Test True 4 3
03 Under the hood
- 1
The list preserves order and duplicates, which can matter to a schedule. The set removes duplicates and is not a positional sequence.
- 2
Building lookup costs work proportional to the input size. It becomes attractive when many membership checks follow.
- 3
If you need a relationship from a name to a record, use a dictionary rather than parallel lists and repeated scans. Be explicit about what happens when keys repeat.
04 Your turn, builder
Build a name-to-duration lookup from task pairs and retrieve the duration of Test.
Reveal one possible solution +
tasks = [("Build", 40), ("Test", 20)]
lookup = dict(tasks)
print(lookup["Test"])05 Check your signal
What is lost when converting a list to a set?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.