You're building a small app for a college fest. You need the order in which teams registered, a fixed set of event timings, a check for whether a roll number has already entered, and a lookup from team name to captain. That's four jobs, and Python gives you four built-in collections. Choosing between a list, tuple, set or dictionary in Python is mostly about asking what you'll do with the data most often.
Pick well and your code is short and fast. Pick badly and you end up writing loops to find things, or fighting errors because something changed that shouldn't have. This lesson compares the four side by side and gives you a short set of questions that decides it.
What you need first: Python lists, Python dictionaries, tuples and sets.
Key terms
- Ordered: items keep the position they were added in, and you can get them back by position.
- Mutable: can be changed after it's created.
- Duplicates allowed: the same value can appear more than once.
- Lookup: finding an item, by position (
items[3]), by key (ages["Ahana"]) or by value (x in items). - Time complexity: how the time an operation takes grows with the number of items, written in Big-O notation, such as O(1) (constant) or O(n) (grows with n).
The four collections side by side
| List | Tuple | Set | Dictionary | |
|---|---|---|---|---|
| Written as | [1, 2, 3] | (1, 2, 3) | {1, 2, 3} | {"a": 1} |
| Ordered | Yes | Yes | No | Yes (since Python 3.7) |
| Can change | Yes | No | Yes | Yes |
| Duplicates | Allowed | Allowed | Not allowed | Keys unique, values can repeat |
| Get by | Position | Position | Can't | Key |
in check speed | Slow (O(n)) | Slow (O(n)) | Fast (O(1)) | Fast on keys (O(1)) |
| Empty one | [] | () | set() | {} |
Four questions that decide it
Ask these in order:
- Do you look things up by a name or ID? Use a dictionary. Roll number to student, product code to price, city to PIN code.
- Do you only care whether something is present, with no duplicates? Use a set. Who has already voted, which words appear in a document.
- Is it a fixed group of values that belong together and shouldn't change? Use a tuple. A (latitude, longitude) point, a (year, month, day) date, a database row.
- Otherwise, for an ordered sequence that grows, shrinks or gets sorted, use a list. Marks in a class, messages in a chat, a to-do list.
The fest app from the opening:
| Job | Choice | Why |
|---|---|---|
| Teams in order of registration | List | Order matters and it grows |
| Event timings | Tuple | Fixed; nobody should edit them in code |
| Roll numbers that have entered | Set | Only "seen or not", and fast checks |
| Team name to captain | Dictionary | Look up by name |
Why the choice affects speed
Say you have 10 lakh registered phone numbers and must check incoming numbers against them. Here's the same check with a list and with a set:
import time
numbers = list(range(1_000_000))
number_set = set(numbers)
to_check = range(999_900, 1_000_000) # 100 lookups near the end
start = time.perf_counter()
found = sum(1 for n in to_check if n in numbers)
list_seconds = time.perf_counter() - start
start = time.perf_counter()
found = sum(1 for n in to_check if n in number_set)
set_seconds = time.perf_counter() - start
print(f"List: {list_seconds:.2f} s Set: {set_seconds:.5f} s")
We don't show an output because the timing depends on your computer. On a typical laptop the list takes a second or more, and the set takes a fraction of a millisecond. The list compares items one by one; the set jumps straight to the right place using a hash.
Here's how long common operations take as the collection grows:
| Operation | List | Set | Dictionary |
|---|---|---|---|
x in c | O(n) | O(1) | O(1) on keys |
Get by position c[i] | O(1) | not possible | not possible |
Get by key c[k] | not possible | not possible | O(1) |
| Add at end / add item | O(1) | O(1) | O(1) |
| Insert or remove at the start | O(n) | O(1) | O(1) |
| Sort | O(n log n) | not possible | not possible directly |
O(1) on sets and dictionaries is the average case; it's what you'll see in practice. If you often add and remove at both ends of a list, collections.deque does both in O(1). It's covered in the standard library module.
The same data, four ways
One small dataset, stored in each collection, to see what each is good at:
# List: ordered, allows repeats, good for "in what order?"
visits = ["Pune", "Goa", "Pune", "Delhi"]
print(visits[0], visits.count("Pune"))
# Tuple: a fixed record
trip = ("Pune", "Goa", "2026-12-20")
origin, destination, date = trip
print(destination)
# Set: unique, fast "have I been there?"
visited = set(visits)
print("Goa" in visited, len(visited))
# Dictionary: look up by city
visit_count = {}
for city in visits:
visit_count[city] = visit_count.get(city, 0) + 1
print(visit_count["Pune"])
Pune 2
Goa
True 3
2
Combining them
Real programs mix collections. Choosing well usually means choosing the right outer and inner types:
# Dictionary of sets: which students are in which club, no duplicates
clubs = {"coding": {"Ahana", "Rohan"}, "music": {"Rohan", "Meera"}}
clubs["coding"].add("Ahana") # already there, no duplicate
print(sorted(clubs["coding"] & clubs["music"]))
# Dictionary with tuple keys: distance between two cities
distance = {("Mumbai", "Pune"): 148, ("Delhi", "Agra"): 233}
print(distance[("Mumbai", "Pune")])
# List of tuples: ordered, fixed records, easy to sort
results = [("Ahana", 88), ("Rohan", 72), ("Meera", 95)]
results.sort(key=lambda r: r[1], reverse=True)
print(results[0])
['Rohan']
148
('Meera', 95)
Nested lists, dictionaries and JSON goes further with mixed data.
Common wrong choices
- A list for lookups by ID. Searching
[s for s in students if s["roll"] == 104]on every request is slow. Build a dictionary keyed by roll number once. - A list for "already seen" checks in a loop. This quietly turns an O(n) program into O(n²). Use a set.
- A dictionary where every value is
True, like{"Ahana": True, "Rohan": True}. That's a set pretending to be a dictionary. - A tuple for data that changes, then converting it to a list and back again every time. Use a list.
- Parallel lists:
names = [...],marks = [...],cities = [...]kept in step by index. One delete and they drift apart. Use a list of dictionaries or tuples instead.
Beyond the built-ins
When none of the four fits perfectly, the standard library has more:
| Need | Use |
|---|---|
| Count how often each item appears | collections.Counter |
| Dictionary that creates missing values automatically | collections.defaultdict |
| Fast adding and removing at both ends (queues) | collections.deque |
| Always get the smallest item fast | heapq |
| A record with named fields | dataclasses or typing.NamedTuple |
| Large tables of numbers | NumPy arrays and pandas DataFrames |
For data science, the rule of thumb is: built-in collections for small, mixed data and program logic; NumPy and pandas once you have thousands of rows of numbers.
Practice
For questions 1 to 4, choose a collection and say why.
- The 12 months of the year, in order, which your program only reads.
Show the answer
A tuple. The order matters and the data never changes. A list would also work, but a tuple says "this is fixed".
- Every word a user has already guessed in a word game, to stop repeat guesses.
Show the answer
A set. You only need "guessed or not", duplicates are pointless, and in must be fast.
- Item codes in a shop mapped to their prices.
Show the answer
A dictionary, {"A101": 49.0, ...}. You look prices up by code.
- The songs in a playlist, which the user can reorder and which may include the same song twice.
Show the answer
A list. Order matters, it changes, and duplicates are allowed.
- This code checks for duplicate roll numbers but is very slow on 1 lakh entries. Fix it.
rolls = [101, 102, 103, 102, 104]
seen = []
duplicates = []
for r in rolls:
if r in seen:
duplicates.append(r)
seen.append(r)
print(duplicates)
Show the answer
r in seen searches a growing list, so the whole loop is O(n²). Make seen a set:
rolls = [101, 102, 103, 102, 104]
seen = set()
duplicates = []
for r in rolls:
if r in seen:
duplicates.append(r)
seen.add(r)
print(duplicates)
[102]
Now each check is O(1) and the loop is O(n).
- Replace these parallel lists with a better structure, then print Rohan's marks.
names = ["Ahana", "Rohan", "Meera"]
marks = [88, 72, 95]
Show the answer
A dictionary keyed by name is the simplest fix here:
names = ["Ahana", "Rohan", "Meera"]
marks = [88, 72, 95]
marks_by_name = dict(zip(names, marks))
print(marks_by_name["Rohan"])
72
If each student had several fields, use a list of dictionaries instead.
Interview questions
When would you use a tuple instead of a list?
For a fixed group of related values that shouldn't change, such as coordinates or a database row, and when you need it as a dictionary key or set member. Tuples signal intent and are hashable when their items are.
Why are dictionary and set lookups O(1) on average?
Both are hash tables. Python computes a hash of the key, uses it to find a slot directly, and compares only the few items in that slot. Lists have no such index by value, so they must scan.
Can dictionary keys be lists?
No. Keys must be hashable, and lists are mutable, so {[1, 2]: "x"} raises TypeError: unhashable type: 'list'. Use a tuple instead.
Key takeaways
- Lookup by name or ID: dictionary. Presence only, no duplicates: set. Fixed record: tuple. Everything else: list.
inis O(n) on lists and tuples but O(1) on sets and dictionary keys, which matters inside loops.- Avoid parallel lists; group related values into dictionaries or tuples.
- Mix collections freely: dictionaries of sets, lists of tuples, dictionaries with tuple keys.
- Reach for
collectionswhen the built-ins don't fit, and pandas or NumPy for large numeric data.
Frequently asked questions
Which Python data structure is fastest?
It depends on the operation. Sets and dictionaries are fastest for lookups by value or key. Lists and tuples are fastest for getting an item by position and for looping in order.
Are dictionaries ordered in Python?
Yes. Since Python 3.7, dictionaries keep the order in which keys were inserted. Sets still have no order.
Should I use a dictionary or a class for a record?
For quick scripts and data from JSON, a dictionary is fine. When the same kind of record appears all over a program, a class or dataclass gives you named fields, defaults and error checking. See Python classes and objects.
What to learn next
- Start working with text in cleaning and splitting text in Python.
- See how algorithms depend on these choices in Big-O notation.
- Model records properly with Python classes and objects.