Choosing the Right Structure
Most of the skill is picking the structure that matches the questions you will ask.
| You need | Use |
|---|---|
| Fast access by position | list |
| Fast lookup by key, or counting | dict |
| Fast "have I seen this?" and no duplicates | set |
| Last in, first out | list as a stack |
| First in, first out | deque |
| Smallest or most urgent first | heap (heapq) |
| Sorted data with fast search | sorted list plus binary search, or a BST |
| Items connected to each other | graph as a dict of lists |
The example times the same question, "is the number in this collection?", on a list and on a set. Both give the right answer; only one stays fast as the data grows.
You need to check millions of times whether a word is in a vocabulary. Which structure?
For each task pick the best structure name from: list, dict, set, deque, heap. Print the five names, one per line, in this task order: count word frequencies, remove duplicates from a list, serve customers first come first served, always get the cheapest item next, read the 4th item by position.
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.