LESSON 17 · NEXT STEPS17 min

Tuples and Sets

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,).

Choose a tuple for a fixed group and a set for distinct values.

Before you start: Lists

Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons

Video lesson: Tuples and Sets

The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube

Read the video transcript

Select a timestamp to watch that moment on YouTube.

  1. 00:00

    Suppose your program stores a point on a map as the pair three and four. The order matters: the first number is one coordinate and the second is another. Now suppose a web page has tags named Python, web, Python, and data. This time you care about which tags are present, and the duplicate Python is not useful. These are different data problems, and Python gives us different containers for them. A tuple is a good fit for a small fixed group in a meaningful order. A set is a good fit for distinct values and membership questions. We will build a function that removes duplicate tags and returns a sorted tuple so the displayed result is stable.

  2. 00:41

    Before coding, predict what it should return for Python, web, Python, and data. The final order will be data, Python, web after alphabetical sorting. Start with a tuple such as coordinates equal to three comma four inside parentheses. You can read the first and second positions with indexes zero and one. You can also unpack the pair into names such as x and y, which makes the meaning of each position clearer. A tuple preserves order. You cannot assign a new value to one of its positions after creating it. That is what we mean when we call the tuple immutable. Be precise about the claim: a tuple can contain a mutable object, such as a list, and that inner list can still change.

  3. 01:28

    For a simple pair of numbers or strings, the fixed-container model is easy to reason about. The website's deeper guide uses a tuple holding an item identifier, a notebook label, and a price. It unpacks those values and prints a readable summary. This works well while the record remains small and its positions are documented. For larger records with many fields, named structures are often easier to maintain. There is also a syntax detail that surprises many learners. Parentheses around a single string do not make a tuple. The comma does. Write a string inside parentheses with a trailing comma, then check its type.

  4. 02:09

    That distinction matters when a function expects a one-item tuple rather than the string itself. Now turn to sets. A set stores distinct elements. Converting a list of tags to a set removes duplicates automatically. In the lesson example, the two Python entries collapse into one. A set is also useful for asking whether an item is present, or whether two collections overlap. The expression Python in tags returns a Boolean answer. You can compare two sets with intersection to keep values present in both, or difference to keep values present in one but absent from the other. The guide compares skills a learner has with skills a project requires.

  5. 02:53

    An intersection finds the skills already covered. A difference finds missing skills. Sets do not promise an order suitable for your display or a screenshot test. Avoid assuming that the printed representation of a set will always list elements the same way. When presentation order matters, call sorted, which gives a list in a predictable order. The lesson's unique tags function turns the input list into a set, sorts it, then wraps the sorted sequence in a tuple. This combines the strengths of both containers: distinct members from the set and a fixed ordered result from the tuple. Run it with Python, web, Python, data and check the sorted tuple.

  6. 03:36

    Try an empty input list as a boundary case. The set is empty, sorting yields an empty list, and the final tuple is empty. No special conditional is required. Sets can themselves contain tuples of simple fixed values, because such tuples are hashable. They cannot contain lists directly; a list can change, so it is not a valid set member. The deeper guide uses a set of student and course pairs to remove repeated relationships. If that sounds abstract, remember the practical question: are these two pieces of information together a distinct record, and do we need to detect duplicates? A tuple pair inside a set expresses exactly that.

  7. 04:18

    Empty curly braces are an easy trap. They create an empty dictionary, not an empty set. If you call add on that value, Python reports that a dictionary has no such method. Use set with empty parentheses to create an empty set, then add a value. Another trap is expecting a set to preserve the same printed order as the original list. The set answers membership questions, but it should not be used as an ordered report. Sort before displaying or comparing text output. A third mistake is writing a one-item tuple without the comma. The value in parentheses remains the original object, so later unpacking or type checks may behave differently than you expect.

  8. 05:04

    Finally, do not claim that every tuple makes a valid set member. A tuple containing a list is still unsuitable, because the inner list is mutable and unhashable. Choose a tuple of fixed values such as strings or integers for this pattern. Your practical task is to make unique tags remove duplicates and return a sorted tuple. Before clicking Run, write down the result you expect for Python, web, Python, and data. Then try the empty list and predict an empty tuple. Try a list with only one tag repeated three times; the result should contain exactly one item. These cases tell you whether deduplication, sorting, and tuple conversion each work.

  9. 05:48

    Use the task checker after your own experiments. It checks more than the displayed list, so returning a fixed sample tuple will not pass. Complete the quiz on tuples, sets, and dictionaries to finish the lesson. For an extra exercise, compare two skill sets and print the missing skills in sorted order. The website guide includes a working example and expected output. The on-screen URL opens the full lesson, where you can run these variations in the browser console and review the step-by-step explanations at your own pace.

Understand the concept

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().

    Browse this lesson’s problem fixes

    Sources and further reading