How it works
A set stores unique unordered items with fast membership testing. A tuple is an immutable sequence, which makes it hashable and usable as a dictionary key.
Use a set to deduplicate or test membership, and a tuple for a fixed record.
Common error
Expecting a set to preserve order. It does not, and relying on the order you observe is fragile.
Worked example
Python
unique = set([3, 1, 3])
point = (2, 5)
print(sorted(unique))
print(point[0])Output
[1, 3]
2Sets remove duplicate membership and are not sequences with a fixed positional order. Tuples provide immutable outer structure and can serve as keys when all their elements are hashable.
Exercises
3.3.1 · Trace
Determine the exact output and explain the state changes.
Python
a = {1, 2, 3}
b = {3, 4}
print(sorted(a & b))
print(sorted(a | b))Show solution
Output
[3]
[1, 2, 3, 4]Intersection keeps common elements; union keeps elements appearing in either set.
3.3.2 · Explain
Why is (1, 2) usable as a dictionary key while [1, 2] is not?
Show solution
The tuple of integers is hashable and immutable in structure. A list is mutable and unhashable. Not every tuple is hashable if it contains unhashable elements.
