LESSON 17 · NEXT STEPS17 min

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

PYTHON
point = (3, 4)
print(point[0])
print(point)
EXPECTED OUTPUT
3
(3, 4)

A tuple stores the first and second coordinate in a fixed order.

02. Remove duplicates

PYTHON
colors = ["red", "blue", "red"]
print(sorted(set(colors)))
EXPECTED OUTPUT
['blue', 'red']

set removes the repeated red; sorted gives a predictable display order.

03. Build a stable tuple

PYTHON
tags = ["web", "python", "web"]
print(tuple(sorted(set(tags))))
EXPECTED OUTPUT
('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.

01 / 03

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.

PYTHON
item = (104, "Notebook", 7.50)
item_id, label, price = item
print(f"{item_id}: {label}")
print(price * 2)
EXPECTED OUTPUT
104: Notebook
15.0
Follow the reasoning
  1. The three names receive tuple values in the same order.
  2. The numeric price can still be used in arithmetic.
  3. Change the tuple to a different price and predict the second line.
02 / 03

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.

PYTHON
learner = {"python", "git", "html"}
required = {"python", "sql", "git"}
known = learner & required
missing = required - learner
print(sorted(known))
print(sorted(missing))
EXPECTED OUTPUT
['git', 'python']
['sql']
Follow the reasoning
  1. & keeps values in both sets; - keeps requirements absent from learner.
  2. sorted turns unordered sets into stable display lists.
  3. Adding sql to learner removes it from missing.
03 / 03

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.

PYTHON
pairs = [("Ada", "Python"), ("Ben", "Python"),
         ("Ada", "Python")]
unique_pairs = set(pairs)
print(sorted(unique_pairs))
print(len(unique_pairs))
print(type(("Python",)).__name__)
EXPECTED OUTPUT
[('Ada', 'Python'), ('Ben', 'Python')]
2
tuple
Follow the reasoning
  1. The repeated Ada–Python pair collapses to one set member.
  2. Sorting stabilizes the printed order without changing the set.
  3. 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 run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnFinish unique_tags(tags) so it removes duplicates and returns a sorted tuple. The prepared list should print ('data', 'python', 'web'). It should also work for an empty list.
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.

    01.What does (5,) create?

    02.What does {} create in Python?

    03.Why sort a set before printing lesson output?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    Expecting a set to preserve duplicates

    COMMON MISTAKE
    print(len(set([1, 1, 2])) == 3)
    FIX
    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

    COMMON MISTAKE
    items = {}
    items.add('python')
    FIX
    items = set()
    items.add('python')

    What happens: AttributeError: a dictionary has no add method.
    Construct an empty set with set().

    Sources and further reading