List vs tuple vs set vs dict in Python
8 min readUpdated
These four are the built-in collections you use every day, and interviewers ask how they differ. This guide puts them side by side, shows each in a short program, and ends with a simple way to choose.
The short answer
list | tuple | set | dict | |
|---|---|---|---|---|
| Written as | [1, 2, 3] | (1, 2, 3) | {1, 2, 3} | {"a": 1} |
| Holds | Items in order | Items in order | Unique items | Key-value pairs |
| Ordered | Yes | Yes | No | Yes (insertion order) |
| Mutable | Yes | No | Yes | Yes |
| Duplicates | Allowed | Allowed | Not allowed | Keys: no. Values: yes |
| Access by | Index | Index | Membership only | Key |
Lookup x in c | O(n) | O(n) | O(1) average | O(1) average (keys) |
| Can be a dict key or set item | No | Yes, if all items are hashable | No (use frozenset) | No |
| Use it for | A collection that changes | A fixed record | Unique items, fast membership, set maths | Lookup by name or id |
In a set and in dict keys, items must be hashable. Numbers, strings and tuples of hashable items are. Lists, sets and dicts are not.
List: an ordered, changeable sequence
Use a list when the order matters and the contents change. It is the default choice.
scores = [72, 88, 65]
scores.append(91) # add at the end
scores[0] = 75 # change an item
scores.remove(65) # remove by value
print(scores)
print(scores[1:3]) # slicing gives a new list
print(sorted(scores))
Output
[75, 88, 91] [88, 91] [75, 88, 91]
Tuple: a fixed record
A tuple cannot change after creation. Use it for a group of values that belong together, such as a point or a row. Python functions that return several values really return a tuple.
point = (3, 4)
x, y = point # unpacking
print(x, y)
def min_max(values):
return min(values), max(values) # returns a tuple
low, high = min_max([4, 9, 2])
print(low, high)
try:
point[0] = 10
except TypeError as error:
print("TypeError:", error)
print(type((5)), type((5,))) # one-item tuple needs a comma
Output
3 4 2 9 TypeError: 'tuple' object does not support item assignment <class 'int'> <class 'tuple'>
Set: unique items and fast membership
A set throws away duplicates and answers "is this in the collection?" in O(1) on average. Use it to remove duplicates and to compare groups.
python_class = {"Asha", "Ravi", "Meena"}
sql_class = {"Ravi", "Tom", "Meena"}
print(sorted(python_class & sql_class)) # in both
print(sorted(python_class | sql_class)) # in either
print(sorted(python_class - sql_class)) # only in Python class
print("Asha" in python_class)
print(len(set([1, 2, 2, 3, 3, 3]))) # remove duplicates
Output
['Meena', 'Ravi'] ['Asha', 'Meena', 'Ravi', 'Tom'] ['Asha'] True 3
A set has no order and no index, so s[0] is an error. If you need the items in order, use sorted(s).
Dict: look things up by key
A dict maps keys to values. Use it when you want to find something by name or id instead of by position.
marks = {"Asha": 88, "Ravi": 72}
marks["Meena"] = 91 # add
marks["Ravi"] = 75 # update
print(marks["Asha"])
print(marks.get("Tom", 0)) # safe lookup with a default
for name, mark in marks.items():
print(name, mark)
counts = {}
for ch in "banana":
counts[ch] = counts.get(ch, 0) + 1
print(counts)
Output
88
0
Asha 88
Ravi 75
Meena 91
{'b': 1, 'a': 3, 'n': 2}Which one should I use?
| I need to… | Use |
|---|---|
| Keep items in order and add or remove them | list |
| Return or store a few fixed values together | tuple |
Use a pair of values as a dict key, such as (row, col) | tuple |
| Remove duplicates, or test membership many times | set |
| Find which items two groups share | set with & |
| Look up a value by name, id or key | dict |
| Count how many times each item appears | dict (or collections.Counter) |
| Keep the first-seen order and remove duplicates | dict.fromkeys(items) |
The speed difference
Looking up an item in a list scans it one by one, so the cost grows with the size. A set or dict jumps straight to the item using its hash. For a large collection that you search many times, this is the difference between a slow solution and a fast one.
names = ["Asha", "Ravi", "Meena", "Tom"]
lookup = set(names)
print("Meena" in names) # scans the list: O(n)
print("Meena" in lookup) # one hash lookup: O(1) on average
Output
True True
Common mistakes
{}is an empty dict, not an empty set. Writeset()for an empty set.(5)is just the number 5. A one-item tuple is(5,).- Putting a list in a set or as a dict key raises
TypeError: unhashable type: 'list'. Convert it to a tuple first. - Using
inon a big list inside a loop. Convert the list to a set once, before the loop. - Changing a list or dict while looping over it. Loop over a copy, or build a new collection.
- Expecting a tuple to be deeply fixed. A tuple that holds a list is fixed, but the list inside can still change.
bad_key = [1, 2]
try:
seen = {bad_key}
except TypeError as error:
print("TypeError:", error)
good_key = tuple(bad_key)
print({good_key})
record = (1, [2, 3])
record[1].append(4) # allowed: the list inside is mutable
print(record)
Output
TypeError: unhashable type: 'list'
{(1, 2)}
(1, [2, 3, 4])Frequently asked questions
What is the main difference between a list and a tuple?
A list can change after it is created, and a tuple cannot. Because of that, a tuple can be a dict key or a set item, and a list cannot.
Is a dict ordered in Python?
Yes. Since Python 3.7 a dict remembers the order in which keys were inserted. A set does not keep any order you can rely on.
Why is a set faster than a list for membership tests?
A set uses a hash table, so it finds an item in O(1) time on average. A list checks items one by one, which is O(n).
Can a dict key be a list?
No. Keys must be hashable, and a list is mutable, so it is not. Use a tuple instead.
Learn it step by step
Practise this, step by step
Short lessons with quizzes, practice and interview questions, from your first program to job-ready.