Lists, dicts and sets: what each operation costs
Python gives you four everyday containers: lists, tuples, dicts and sets. They can all hold the same data, but some questions take one of them a second and another an hour. This lesson shows what each is for, what its operations cost, and how to pick one from the question you are asked.
Foundations · Python for data engineers · Bronze · Built-in data structures, lesson 1 of 3
On this page
In plain words first
list: a numbered queuequeue: A line of items served first in, first out: you add at the back and take from the front. Learn more →
tuple: a printed ticket
dict: a phone book
set: a guest list
The whole lesson follows from those pictures: walking a queue is slow when it is long, while a phone book or a guest list answers straight away.
Four containers, four jobs
Almost every data task in Python is built from four containers. Picking the right one is usually the difference between a solution that runs in a second and one that times out, so interviewers watch this choice closely.
| Container | Use it for | Example |
|---|---|---|
list | An ordered sequence you append to and index by position | The orders of the day, in arrival order |
tuple | A fixed group of values; hashable, so it can be a dict key | (restaurant_id, day) |
dict | Look up a value by key | Rider id → rider name |
set | Membership and uniqueness | The ids of restaurants that are open |
What each operation costs
A dict and a set are hash tables: Python hashes the key, jumps to its slot and checks it, so a lookup takes the same time whether there are ten keys or ten million. A list has no index by value: x in my_list compares x with every element until it finds a match.
| Operation | list | dict / set |
|---|---|---|
x in c | O(n): scans every element | O(1) on average |
Get by position c[i] | O(1) | not available |
Get by key d[k] | not available | O(1) on average |
| Append / add | O(1) amortised at the end | O(1) on average |
| Insert or remove at the front | O(n): every element shifts; use collections.deque for O(1) | not available: no front |
import time open_ids = list(range(200_000)) open_set = set(open_ids) wanted = list(range(199_000, 201_000)) t0 = time.perf_counter() hits_list = sum(1 for r in wanted if r in open_ids) t1 = time.perf_counter() hits_set = sum(1 for r in wanted if r in open_set) t2 = time.perf_counter() print("found with the list:", hits_list, "| found with the set:", hits_set) print("set is faster:", (t2 - t1) < (t1 - t0))
Output from a real run
found with the list: 1000 | found with the set: 1000 set is faster: True
Two thousand lookups in a list of 200,000 are 400 million comparisons in the worst case; in a set they are two thousand hash probes. Whenever a loop asks "have I seen this?" or "is this allowed?", build a set or dict first.
Keys must be hashable
A dict key or set member must be hashable: its hash may never change. Strings, numbers and tuples of hashable values are; lists, dicts and sets are not, because they can change after being stored. To key on several fields, use a tuple.
deliveries = {} deliveries[("rest-7", "2026-03-01")] = 41 try: deliveries[["rest-7", "2026-03-02"]] = 12 except TypeError as e: print("TypeError:", e) print(deliveries)
Output from a real run
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')
{('rest-7', '2026-03-01'): 41}A list as a stack
Think of a pile of plates: you put a plate on top, and you take the top one off first. That is a stack, "last in, first out". A plain list is a perfect stack as long as you only touch its end: append(x) puts on top, pop() takes the top off, and stack[-1] peeks at it. All three are O(1). (Taking from the front is a queue, "first in, first out": use a deque for that, from the collections lesson.)
cart = [] history = [] # a stack of actions: the newest is at the end for dish in ["dosa", "chai", "vada"]: cart.append(dish) history.append(("added", dish)) action, dish = history.pop() # take the top of the stack cart.remove(dish) print("undid:", action, dish, "| cart:", cart) print("next undo would be:", history[-1]) print("empty stack is falsy:", not [])
Output from a real run
undid: added vada | cart: ['dosa', 'chai']
next undo would be: ('added', 'chai')
empty stack is falsy: TrueStacks answer questions about nesting. When things open and close inside each other (brackets, nested JSON, pipeline steps that start and finish inside a parent step), whatever closes must match the most recent thing still open, and that is always the top of the stack. Check that the stack is not empty before you pop(): popping an empty list raises IndexError.
Choosing from the question
- "Have I seen X?" or "remove duplicates": a set.
- "The most recent thing still open" (undo, nesting, matching pairs): a list used as a stack.
- "Find X by its id" or "count per key": a dict.
- "The complement of X" (a partner that sums to a target): a dict from value to position, filled as you go.
- "Keep the order and index by position": a list.
- "A record that should not change", or a composite key: a tuple.
orders = [("o1", "asha"), ("o2", "ben"), ("o3", "asha"), ("o4", "ben")] first_seen = {} for order_id, customer in orders: if customer in first_seen: print(order_id, "repeats", first_seen[customer]) break first_seen[customer] = order_id
Output from a real run
o3 repeats o1
Common mistakes
- Testing membership in a list inside a loop — That is O(n) per test and O(n²) overall. Convert to a set once, before the loop.
- Using a list as a dict key — Lists are unhashable. Use a tuple for composite keys.
- Relying on set order — Sets have no defined order. Sort when the output order matters.
- Using a list as a queue — list.pop(0) shifts every element: O(n). A stack uses pop() at the end; a queue needs collections.dequedeque: A double-ended queue from collections: adding or removing at either end is O(1), unlike a list, where removing from the front is O(n). Learn more →.
Key takeaways
- dict and set lookups are O(1) on average; list membership is O(n).
- Keys must be hashable: tuples yes, lists no.
- Build a set or dict before a loop that asks "seen it?" or "find by key".
- A list is a stack when you only append() and pop() at the end: O(1) each.
- Pick the container from the question being asked.
Interview prep
THE QUESTION
"Why is checking `x in my_list` slow, and what would you use instead?"
in compares x with every element: O(n), and O(n·m) inside a loop over m items. A set or dict hashes the value and checks one slot, O(1) on average. So I convert the list to a set once, before the loop, which makes the loop O(m). The trade-off is extra memory for the set, and the values must be hashable.Avoid: "a set is just a list without duplicates". It is a hash table: the point is O(1) membership, not just uniqueness.
Follow-ups · answer out loud, then open
Follow-up"Why can a tuple be a dict key but a list cannot?"
Scenario"A job checks 2 million event ids against a list of 500,000 blocked ids and takes hours. Fix it."
Trap"dict lookups are always O(1)."
Check yourself
4 questionsWhich is O(1) on average?
Show the answer
x in a_set. Sets are hash tables; the list operations scan.
Which can be a dict key?
Show the answer
("a", 1). Only the tuple is hashable.
You must look up 1 million ids in a list of 1 million allowed ids. Best first step?
Show the answer
Turn the allowed ids into a set. Then each lookup is O(1) instead of O(n).
stack = ["a", "b", "c"]; stack.pop() returns...
Show the answer
"c". pop() takes from the end, the top of the stack: last in, first out.
Practise this
Problems that use this, graded on hidden tests
- Two SumDSA for data engineers Easy
- Invert a DictionaryCore Python & data structures Easy
- First Non-Repeating CharacterDSA for data engineers Easy
Keep going
Up next · Built-in data structures · lesson 2 of 3 · 5 min readComprehensions
List, dict and set comprehensions, filtering versus choosing, nesting, and generator expressions.
Related lessons
Counter, defaultdict and dequePython for data engineers · 5 min read
Big-O and performance for data engineers
Previous: Files, JSON, CSV and dates
Primary sources: Time complexity of built-in operations (Python wiki) · Built-in types