Beginner 5 min

Tuples and sets

A tuple holds values in a fixed sequence, while a set keeps unique values.

How it works

Choose based on what a later operation needs. Keep a location as a tuple because first and second have different meanings. Keep visited room IDs as a set because you only need to know whether a room was already seen. If you need both order and repeated values, use a list.

Walk through an example

A coordinate like (4, 9) groups two values. set([4, 4, 9]) contains two distinct numbers. Use in to check membership.

What to watch for

Sets do not promise a particular display order. Use sorted() if a report requires predictable ordering.

Code example

point = (4, 9)
print(point[0])
print(sorted(set([3, 3, 1])))

Check your understanding

How many unique values are here?

See the example and explanation
Worked example
Given [3, 3, 1, 3, 1]
Answer 2

The repeated 3s collapse to one value and the repeated 1s collapse to one value.

Open practice problem
Next lessonLists and dictionaries