You already know lists. Python has two more ways to keep several values together: tuples and sets. A tuple is like a list that can never change. A set is a bag of unique items with no fixed order. Both take ten minutes to learn, and you will use them all the time.
TUPLES: VALUES THAT BELONG TOGETHER
A tuple uses round brackets instead of square ones. Use it for a small group of values that make sense as one thing: a spot on a map, a colour, a date.
pos = (3, 7)
print(pos)
print(pos[0])
print(len(pos))(3, 7)
3
2
Indexing and len() work just like with a list. Positions start at 0.
UNPACKING: ONE NAME PER ITEM
The best tuple trick: give each item its own name in one line.
pos = (3, 7)
x, y = pos
print("x is", x)
print("y is", y)x is 3
y is 7
The same trick swaps two variables, no helper variable needed:
a = "sword"
b = "shield"
a, b = b, a
print(a, b)shield sword
TUPLES CAN'T CHANGE
Once a tuple is made, you can't add, remove or replace its items. Python stops you with a TypeError.
pos = (3, 7)
pos[0] = 5
# TypeError: 'tuple' object does not support item assignment
That sounds like a limit, but it is a feature. If a value should never change by accident, like the size of the game board, a tuple protects it. To "move", build a new tuple and store it in the same name:
pos = (3, 7)
pos = (pos[0] + 1, pos[1])
print(pos)(4, 7)
RETURNING TWO VALUES FROM A FUNCTION
When a function returns several values separated by commas, Python packs them into a tuple. Unpack them where you call it.
def min_max(scores):
return min(scores), max(scores)
low, high = min_max([12, 40, 7, 25])
print(low, high)7 40
hero = ("Ada", 30, "mage")
name, hp, job = hero
print(hp + 5)hp is the number 30, and 30 + 5 is 35. You only get an error if you try to change the tuple itself.SETS: ONLY UNIQUE ITEMS
A set uses curly brackets and keeps each value only once. Duplicates simply disappear.
rolls = {4, 2, 4, 6, 2}
print(len(rolls))3
The most common use: turn a list into a set to remove duplicates, or to count how many different things there are.
visits = ["Ada", "Bo", "Ada", "Kai", "Bo"]
unique = set(visits)
print(len(unique))
print(sorted(unique))3
['Ada', 'Bo', 'Kai']
unique[0] is an error. When you need them in order, use sorted(my_set), which gives you a sorted list.ADDING, REMOVING AND CHECKING
Unlike tuples, sets can change. Use add() and discard(). Checking with in is very fast, even for huge sets.
keys = set()
keys.add("red")
keys.add("blue")
keys.add("red")
keys.discard("blue")
print(keys)
print("red" in keys)
print("gold" in keys){'red'}
True
False
Adding "red" a second time does nothing: it is already there.
COMPARING TWO SETS
Sets can answer questions like "what do these two have in common?" with one symbol.
mine = {1, 2, 3, 4}
yours = {3, 4, 5}
print(mine & yours)
print(mine | yours)
print(mine - yours){3, 4}
{1, 2, 3, 4, 5}
{1, 2}
&intersection: in both sets.|union: in either set.-difference: in the first set but not the second.
tags = set(["fire", "ice", "fire", "ice", "rock"])
tags.add("fire")
print(len(tags))LIST, TUPLE OR SET?
- List
[ ]: an ordered collection you will change. A shopping list, a high-score table. - Tuple
( ): a small fixed group that belongs together. Coordinates, an RGB colour. - Set
{ }: unique items where order doesn't matter. Visited rooms, collected badges.
COMMON BEGINNER MISTAKES
(5) is just the number 5 in brackets. A one-item tuple needs a comma: (5,).{}. Empty curly brackets make an empty dictionary. Use set() for an empty set.my_set[0] raises a TypeError because sets have no positions. Loop over it, or use sorted() first.x, y = (1, 2, 3) raises a ValueError. You need one name per item.PRACTICE IT, DON'T JUST READ IT
Tuple Tomb in Dict Dungeon has you unpack tuples and count unique items with sets, one swipe-sized step at a time.
PLAY DICT DUNGEON ▸FAQ
What is the difference between a list and a tuple in Python?
A list can be changed after it is made: you can add, remove and replace items. A tuple cannot be changed. Lists use square brackets, tuples use round brackets.
How do I remove duplicates from a list in Python?
Turn it into a set: set(my_list). If you need a list back in a fixed order, use sorted(set(my_list)).
How do I make an empty set in Python?
Use set(). Empty curly brackets {} make an empty dictionary, not a set.
Why does my set print in a different order?
Sets have no order. Python stores items in whatever way makes lookups fast, so the printed order can differ. Use sorted() when order matters.