Python lists vs tuples vs sets
Python has three common ways to keep several values together. A list can change and keeps order, a tuple is a fixed record, and a set forgets duplicates. Each example below was run, and the output shown is exact.
Lists: order, and they can change
A list is the default collection: append adds to the end, and a for loop walks the items in order. Use a list when the group will grow or shrink, such as an inventory.
parts = ["wrench"]
parts.append("cable")
print(parts)Output:
['wrench', 'cable']
Tuples: a fixed record
A tuple cannot be edited in place. That makes it a good fit for a coordinate or any pair you want to unpack into two names. Returning two values from a function also builds a tuple.
point = (3, 4) x, y = point print(x) print(y)
Output:
3 4
Sets: unique items
A set drops duplicates and answers "is this in here?" quickly. The empty set is set(), because {} is an empty dictionary. set(needed) <= set(have) asks whether every needed item is already present.
needed = {"wrench", "cable"}
have = ["wrench", "cable", "chip", "wrench"]
print(needed <= set(have))Output:
True
Common questions
- Can I use a tuple as a dictionary key?
- Yes, because a tuple cannot change. A list cannot be a key. That is one reason coordinates are often tuples.
- How do I make an empty set?
- Call set(). Writing {} gives you an empty dictionary.
- When should I pick a set over a list?
- When duplicates do not matter and you care about membership, such as "do I have every part of this recipe?"