Lists, Dicts, Sets & Tuples — When and Why
Half of writing clean logic is just picking the right container to hold your data. Good news — these four cover almost everything, and choosing between them is simpler than it looks.
The idea, in one line
Each container is good at one job: a list keeps order, a dict looks things up by name, a set keeps only unique items, and a tuple is a fixed record that never changes.
List — ordered and changeable
Written with [ ]. Reach for it when order matters and you'll add or remove items — a queue of test cases, or log lines in the order they arrived. Core moves: append (add to the end), pop (remove and hand back), len (count).
Dict — look up by name
Written with { } as key: value pairs. You look things up by their key instead of their position — perfect for a parsed API response or a tally of each error. Loop the pairs with d.items(). Keys have to be unchangeable things (a str, a number, a tuple).
Set — unique, fast membership
Unordered, with no duplicates allowed. It shines at two jobs: dropping duplicates and answering "is x in here?" quickly. It also does set maths:
a & b— items in both (intersection)a | b— items in either (union)a - b— items inabut notb(difference)
Tuple — a fixed record
Like a list, but it can't be changed once made. Written with ( ). Use it for a group that shouldn't wobble, like an (endpoint, method) pair. Because it never changes, a tuple can even be used as a dict key.
See it work
# Count how often each status code appears in a run
run = [200, 404, 200, 500, 404, 200]
counts = {} # dict: code -> how many times
for code in run:
counts[code] = counts.get(code, 0) + 1
print(counts) # {200: 3, 404: 2, 500: 1}
# Which distinct codes did we see? (a set drops duplicates)
print(set(run)) # {200, 404, 500}
# Did we miss an expected code? (set difference)
expected = {200, 201, 404}
print(expected - set(run)) # {201} -> never returnedRead it top to bottom: the dict answers how many of each, the set answers which distinct ones, and subtracting sets tells you what's missing. Same data, three different questions, each container doing what it's best at.
Advanced — why a dict and set are so fast
Looking up a key in a dict, or checking if something is in a set, takes about the same tiny amount of time whether you hold 10 items or 10 million. A list can't do that — to check if a value is in a list, Python walks the whole thing. So when you find yourself asking "is this in here?" a lot, a set or dict is usually the faster choice.
Grounded in the official Python tutorial (Data Structures)
All lessons in Python Foundations & The 6-Step Method
- Variables, Types, Control Flow & Functions
- Lists, Dicts, Sets & Tuples — When and Why
- String Manipulation Patterns
- The 6-Step Method — A Worked Example
- Hand-Tracing — Where Logic Actually Grows