Lists aren't always the right tool. A tuple and a set each trade away one of a list's properties in exchange for something useful.
A tuple looks like a list but uses parentheses, and once created, its contents can't be changed:
point = (10, 20)
print(point[0]) # 10
# point[0] = 5 # TypeError — tuples don't support item assignmentUse a tuple when a fixed, small group of values genuinely shouldn't change after creation — coordinates, an RGB color, a function returning more than one value:
def min_max(numbers):
return min(numbers), max(numbers) # returns a tuple
lowest, highest = min_max([4, 9, 1, 7]) # unpacked into two variables
print(lowest, highest) # 1 7A set automatically discards duplicates and has no guaranteed order — useful whenever "does this exist" and "no repeats" matter more than sequence:
numbers = {1, 2, 2, 3, 3, 3}
print(numbers) # {1, 2, 3} — duplicates are gone
print(3 in numbers) # True — checking membership is very fast on a setSets support the same operations as sets in mathematics — genuinely useful for comparing two collections:
a = {1, 2, 3}
b = {2, 3, 4}
print(a | b) # {1, 2, 3, 4} — union: everything in either
print(a & b) # {2, 3} — intersection: in both
print(a - b) # {1} — difference: in a but not b| Type | Choose when |
|---|---|
| list | Order matters, you'll change the contents, duplicates are fine |
| tuple | Order matters, the contents should never change |
| set | Order doesn't matter, duplicates should be impossible |