Tuples and Sets
Choose a tuple for a fixed group and a set for distinct values.
Video coming to YouTube
Work through the full lesson and run its code while the video is being prepared for publication.
Understand the concept
A tuple groups values in a fixed order and cannot have its items replaced after creation. Use parentheses for a typical tuple, such as coordinates = (3, 4). A one-item tuple needs a trailing comma: (3,).
A set keeps distinct elements and supports membership tests. It has no meaningful display order, so sort a set before printing when you need predictable output. Use set() for an empty set; {} creates an empty dictionary.
In the practice task, set removes repeated tags, sorted arranges them alphabetically, and tuple makes the returned result a fixed group. The result is stable even if the original list contains duplicates in a different order.
- Tuple items have a fixed order and cannot be reassigned
- Sets remove duplicates and are unordered
- tuple(sorted(set(values))) returns a predictable fixed result
See it step by step
Read the code, predict the output, then compare it with the result.
01. A fixed coordinate
point = (3, 4)
print(point[0])
print(point)3
(3, 4)A tuple stores the first and second coordinate in a fixed order.
02. Remove duplicates
colors = ["red", "blue", "red"]
print(sorted(set(colors)))['blue', 'red']set removes the repeated red; sorted gives a predictable display order.
03. Build a stable tuple
tags = ["web", "python", "web"]
print(tuple(sorted(set(tags))))('python', 'web')The three operations remove duplicates, sort, and freeze the result into a tuple.
A closer look
Follow the reasoning, inspect each result, then try the suggested changes in the console below.
Use a tuple as a small record
A tuple is useful when several values belong together and their positions have a clear meaning, such as an item identifier, a label, and a price. Unpacking gives each position a readable name at the point of use. That is safer than scattering record[0] and record[2] throughout a program, where it is easy to mix positions up. A tuple itself cannot have an element replaced after creation.
That last rule is called immutability, but it applies to the tuple container, not automatically to objects inside it. A tuple containing a list can still contain a list whose items change. For simple fixed records, use numbers and strings; for larger data models, a named tuple or dataclass can give fields explicit names. Try swapping the order of the label and price to see why position matters.
item = (104, "Notebook", 7.50)
item_id, label, price = item
print(f"{item_id}: {label}")
print(price * 2)104: Notebook
15.0- The three names receive tuple values in the same order.
- The numeric price can still be used in arithmetic.
- Change the tuple to a different price and predict the second line.
Compare groups with set operations
Sets are useful when the question is about membership rather than order. The intersection of two sets contains items present in both; the difference contains items present only in the first. For example, compare skills a person has with skills a project requires. Duplicate skill names do not change the answer, because a set keeps one instance of each value.
The set's printed order is not a dependable part of the result. Sort it before displaying or testing so the output is predictable. Membership checks such as 'python' in skills express the question directly. Try adding 'sql' to the learner set below and predict which of the two lists changes.
learner = {"python", "git", "html"}
required = {"python", "sql", "git"}
known = learner & required
missing = required - learner
print(sorted(known))
print(sorted(missing))['git', 'python']
['sql']- & keeps values in both sets; - keeps requirements absent from learner.
- sorted turns unordered sets into stable display lists.
- Adding sql to learner removes it from missing.
A set can contain fixed pairs
A set element must be hashable: its hash value must remain stable while it is stored. A tuple is hashable when all its elements are hashable; a pair of strings works. A list cannot be a set element because its contents can change. This makes a set of tuples handy for distinct relationships, such as pairs of city codes or student and course identifiers.
A one-item tuple needs a trailing comma: ('python',) is a tuple, while ('python') is just a string in parentheses. Use type() when that distinction is surprising. The example below deduplicates repeated pairs and sorts them only for display. Try changing one pair's second value and predict whether the number of unique pairs changes.
pairs = [("Ada", "Python"), ("Ben", "Python"),
("Ada", "Python")]
unique_pairs = set(pairs)
print(sorted(unique_pairs))
print(len(unique_pairs))
print(type(("Python",)).__name__)[('Ada', 'Python'), ('Ben', 'Python')]
2
tuple- The repeated Ada–Python pair collapses to one set member.
- Sorting stabilizes the printed order without changing the set.
- The comma, not the parentheses alone, creates the one-item tuple.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Use set(tags) to keep one copy of each tag, sorted(...) for a stable order, and tuple(...) for the return type.
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Expecting a set to preserve duplicates
print(len(set([1, 1, 2])) == 3)print(len(set([1, 1, 2])) == 2)What happens: It prints False because a set has only two distinct values.
A set keeps one copy of each equal value.
Using {} for an empty set
items = {}
items.add('python')items = set()
items.add('python')What happens: AttributeError: a dictionary has no add method.
Construct an empty set with set().