WeCodeAcademy

Choosing the Right Structure

Most of the skill is picking the structure that matches the questions you will ask.

You needUse
Fast access by positionlist
Fast lookup by key, or countingdict
Fast "have I seen this?" and no duplicatesset
Last in, first outlist as a stack
First in, first outdeque
Smallest or most urgent firstheap (heapq)
Sorted data with fast searchsorted list plus binary search, or a BST
Items connected to each othergraph 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.

Examplepython
Open in editor »
Quick check

You need to check millions of times whether a word is in a vocabulary. Which structure?

Your turn: write the code

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.