Sets and Tuples
A tuple is a fixed group of values in round brackets. A set is a collection in curly brackets that never holds the same value twice.
Use a tuple when a few values belong together, like the four squares of one line. Use a set when you only care about which values you have, not how many times you added them.
Making a tuple
A tuple works like a list for reading: index it, count it, loop over it.
line = ("1A", "2A", "3A", "4A")
print(line[0])
print(len(line))
line[0] is the first square, "1A". len(line) is 4.
A tuple cannot be changed after it is made. line[0] = "5A" is an error. To
get a different tuple, make a new one.
Order matters in a tuple
Two tuples are equal only if they hold the same values in the same order:
print(("1A", "2A") == ("1A", "2A"))
print(("1A", "2A") == ("2A", "1A"))
The second line prints False, because the order is different.
Making a set
Start an empty set with set(), not {}. {} makes an empty dictionary.
Add values with .add():
squares = set()
squares.add("1A")
squares.add("2A")
squares.add("1A")
print(len(squares))
"1A" is added twice, but the set keeps it once. len(squares) is 2.
set() also turns a list into a set, dropping the repeats:
rolls = [3, 5, 3, 6, 5]
print(len(set(rolls)))
The list has five rolls, but only three different values.
Tuples inside a set
A set can hold tuples, because tuples cannot change. A set cannot hold lists. This makes a set of tuples a good way to collect lines with no repeats:
lines = set()
lines.add(("1A", "2A", "3A", "4A"))
lines.add(("1A", "1B", "1C", "1D"))
lines.add(("1A", "2A", "3A", "4A"))
print(len(lines))
print(sorted(lines))
The first line is added twice but stored once, so len(lines) is 2. A set
has no order, so use sorted() to print it in a fixed order.
Note: print(lines) on its own can show the items in any order.
See also: Lists, Membership Testing.
Your turn
Add three lines: add the tuple ("1B", "2B", "3B", "4B") to lines, add
("1A", "2A", "3A", "4A") again, then print how many lines the set holds.
lines = set()
lines.add(("1A", "2A", "3A", "4A"))
# add ("1B", "2B", "3B", "4B"), add ("1A", "2A", "3A", "4A") again, then print len(lines) (three lines)
Expected output
2
Practise this in the free Python course, where every exercise checks your code instantly.