Python has three basic collections to store several values: list, tuple and set. Choosing the right one makes the code clearer and safer.
List, tuple or set
| List | Tuple | Set | |
|---|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) | {1, 2, 3} |
| Ordered (indexes) | yes | yes | no |
| Allows repeats | yes | yes | no |
| Can be modified | yes | no | yes |
Check in | slow with lots of data | slow with lots of data | very fast |
| Use it for… | a collection that grows or changes | a fixed record of related data | unique values and comparing collections |
Quick rules
- If order and repeats matter, use a list.
- If the data belongs together and must not change (a coordinate, a date), use a tuple.
- If you only care about which values exist, without repeats, use a set.
Converting between them
data = [3, 1, 3, 2, 1]
print(tuple(data)) # (3, 1, 3, 2, 1)
print(set(data)) # {1, 2, 3}
print(list(set(data))) # list without repeats (order not guaranteed)
print(sorted(set(data))) # [1, 2, 3]
Common mistakes
Trying to modify a tuple. It raises TypeError. If you need to change the data, use a list.
t = (1, 2, 3)
t[0] = 9
# TypeError: 'tuple' object does not support item assignment
Creating an empty set with braces. {} is a dictionary. Use set().
Using remove on something that does not exist. remove raises KeyError; discard does not.
s = {1, 2}
s.discard(5) # nothing happens
s.remove(5) # KeyError: 5
Asking for an index of a set. Sets have no positions:
s = {10, 20, 30}
print(s[0])
# TypeError: 'set' object is not subscriptable
Putting a list inside a set. The elements of a set must be immutable, so a list does not work, but a tuple does:
s = set()
s.add((1, 2)) # correct: a tuple
s.add([1, 2]) # TypeError: unhashable type: 'list'
Forgetting the comma in a one-element tuple. (5) is a number; the tuple is (5,).
Relying on the order of a set. If you need an order, apply sorted() before showing it.
Review what you learned in Student ranking and Guest lists.