Python has four everyday collections. Picking the right one makes code simpler and faster, and "list vs tuple" or "list vs set" is a standard interview question.
List: an ordered, changeable sequence
cities = ["Pune", "Indore", "Pune", "Surat"]
cities.append("Nagpur")
cities[0] = "Mumbai"- Keeps order, allows duplicates, can change.
- Use for sequences you will add to, sort or loop over: daily sales figures, a list of file names.
Tuple: an ordered, fixed sequence
location = (18.52, 73.86) # latitude, longitude
row = ("ORD-1042", "Pune", 860)- Keeps order, allows duplicates, cannot change after creation.
- Use for fixed groups of related values, function results returning several values, and dictionary keys made of several parts.
Set: unique values, no order
jan_buyers = {"C1", "C2", "C3"}
feb_buyers = {"C2", "C3", "C4"}
jan_buyers & feb_buyers # bought in both months
jan_buyers - feb_buyers # bought in Jan, not Feb
jan_buyers | feb_buyers # bought in either- No duplicates, no guaranteed order, very fast membership checks (
"C2" in jan_buyers). - Use to deduplicate, and for "in both / only in one" comparisons, exactly like SQL's INTERSECT and EXCEPT.
Dictionary: key-value lookup
price = {"Notebook": 60, "Pen": 10, "Stapler": 150}
price["Pen"]
price["Marker"] = 35
for item, p in price.items():
print(item, p)- Unique keys, each mapped to a value; fast lookup by key; keeps insertion order.
- Use for lookups (code โ name), counting, grouping and representing records (a row as
{"id": 1, "city": "Pune"}).
Quick comparison
| List | Tuple | Set | Dictionary | |
|---|---|---|---|---|
| Ordered | Yes | Yes | No | Yes (insertion) |
| Duplicates | Yes | Yes | No | Keys: no |
| Changeable | Yes | No | Yes | Yes |
| Fast "is x in it?" | No | No | Yes | Yes (keys) |
| Example | Daily sales | (lat, lon) | Unique customers | Product โ price |
Why lookup speed matters
Checking x in my_list scans the list item by item. With a few hundred thousand items checked in a loop, that becomes very slow. Converting to a set or dictionary makes each check almost instant.
valid_ids = set(customer_ids) # build once
clean = [o for o in orders if o["customer_id"] in valid_ids]Common mistakes
- Using a list as a lookup table and looping to find matches.
- Expecting a set to keep order.
- Trying to change a tuple (convert to a list first).
- Using a mutable list as a dictionary key (not allowed; use a tuple).
Practise
Work through lists, tuples and sets and dictionaries. Each set includes the counting and comparison patterns analysts use daily.
Practise what you just read
Reading helps; writing the code yourself is what sticks. Start here: