🧷
Coding🎓 Ages 14-18Intermediate 13 min read

Python Tuples and Sets

Learn Python tuples and sets: immutable tuples, tuple unpacking, returning multiple values, plus sets for unique items and fast membership and set operations. Runnable code, a worked example and a quiz.

Key takeaways

  • A tuple is an ordered, immutable sequence written with parentheses
  • Tuple unpacking assigns several variables at once, and lets functions return multiple values
  • A set is an unordered collection that automatically removes duplicates
  • Sets give very fast membership tests with the in operator
  • Set operations like union (|), intersection (&) and difference (-) compare collections

Beyond the list

You've probably been using lists as your everyday collection. Lists are flexible — you can change, add and remove items freely. But that flexibility isn't always what you want. Sometimes you need data that is guaranteed never to change, and sometimes you need a collection that automatically removes duplicates and answers "is this in here?" almost instantly. Python provides two more collection types for exactly these jobs: tuples and sets.

Tuples: fixed sequences

A tuple is an ordered sequence of values, just like a list, but it is immutable — once you create it, you cannot change its contents. You write a tuple with parentheses:

point = (3, 5)
print(point)        # (3, 5)
print(point[0])     # 3
print(point[1])     # 5
print(len(point))   # 2

Reading it line by line:

  • point = (3, 5) creates a tuple with two items, perfect for representing a coordinate.
  • point[0] and point[1] read items by index, exactly as with a list. Indexing still starts at 0.
  • len(point) reports how many items there are.

The difference shows up the moment you try to change one:

point = (3, 5)
# point[0] = 9      # this line would crash with a TypeError

Trying to assign to point[0] raises a TypeError because tuples are immutable. This is a feature: it protects data that should stay constant, like a fixed coordinate, a colour as (255, 0, 0), or a date as (2026, 5, 30).

A small gotcha: a tuple with a single item needs a trailing comma, (5,), otherwise Python reads (5) as just the number 5 in brackets.

Tuple unpacking

One of the most elegant tricks in Python is unpacking, which spreads a tuple's values across several variables in one line:

point = (3, 5)
x, y = point
print(x)    # 3
print(y)    # 5
  • x, y = point matches the variables to the tuple's items in order: x gets 3, y gets 5.

This also gives the classic one-line variable swap:

a = 1
b = 2
a, b = b, a
print(a, b)   # 2 1

The right side b, a builds the tuple (2, 1), which is then unpacked back into a and b — swapping them with no temporary variable needed.

Returning multiple values from a function

Tuples power one of the most useful patterns in real code: a function that hands back several results at once. If you've studied functions and parameters, this extends what return can do.

def min_and_max(numbers):
    return min(numbers), max(numbers)

low, high = min_and_max([8, 3, 11, 6])
print(low)    # 3
print(high)   # 11

How it works:

  • return min(numbers), max(numbers) returns a tuple (3, 11) — the comma creates a tuple even without brackets.
  • low, high = min_and_max(...) unpacks that tuple so each result lands in its own clear variable.

This is far cleaner than returning a list and pulling out result[0] and result[1] by index.

Sets: collections of unique items

A set is an unordered collection that cannot contain duplicates. You write one with curly braces:

colours = {"red", "green", "blue"}
print(colours)            # order may vary, e.g. {'blue', 'green', 'red'}

numbers = {1, 2, 2, 3, 3, 3}
print(numbers)            # {1, 2, 3}
  • The duplicates in {1, 2, 2, 3, 3, 3} are silently removed, leaving {1, 2, 3}.
  • Sets are unordered, so you cannot do colours[0], and the printed order may differ from how you typed it.

A classic use is removing duplicates from a list by converting to a set and back:

names = ["Sam", "Ada", "Sam", "Lee", "Ada"]
unique = list(set(names))
print(len(unique))    # 3

set(names) keeps one of each name, then list(...) turns it back into a list. The count drops from five to three.

Fast membership testing

Checking whether an item is in a collection uses the in keyword for both lists and sets — but sets are built to answer this very quickly, even when they hold thousands of items:

allowed = {"admin", "editor", "viewer"}

print("editor" in allowed)   # True
print("guest" in allowed)    # False

For a small collection the speed difference doesn't matter, but if you repeatedly check membership against a large collection, a set is dramatically faster than scanning a list item by item.

Set operations

Sets shine when you want to compare two collections. The operators mirror the maths you may know from Venn diagrams:

maths = {"Ada", "Sam", "Lee"}
art   = {"Sam", "Lee", "Kim"}

print(maths | art)   # union: everyone in either club
print(maths & art)   # intersection: in BOTH clubs
print(maths - art)   # difference: in maths but NOT art
  • maths | art is the union — everyone in either set: {'Ada', 'Sam', 'Lee', 'Kim'}.
  • maths & art is the intersection — only people in both: {'Sam', 'Lee'}.
  • maths - art is the difference — in maths but not art: {'Ada'}.

These three operators turn awkward comparison loops into a single readable line.

Worked example: analysing two friend lists

Let's pull tuples and sets together in a small program that compares the music tastes of two friends.

def compare_tastes(a, b):
    shared = a & b
    only_a = a - b
    only_b = b - a
    return shared, only_a, only_b

alex = {"rock", "pop", "jazz", "indie"}
robin = {"pop", "jazz", "classical"}

both, just_alex, just_robin = compare_tastes(alex, robin)

print("Both like:", both)            # {'pop', 'jazz'}
print("Only Alex:", just_alex)       # {'rock', 'indie'}
print("Only Robin:", just_robin)     # {'classical'}

How it works:

  1. compare_tastes takes two sets and uses & and - to work out what's shared and what's unique to each person.
  2. It returns a tuple of three sets.
  3. The call unpacks that tuple into both, just_alex, and just_robin in a single clear line.

This combines every idea in the lesson: sets remove duplicates and compare collections, while a tuple bundles up multiple return values that unpacking then spreads into named variables.

Try it yourself

Write a program that analyses a sentence:

  • Take a sentence such as text = "the cat sat on the mat the cat".
  • Split it into words with words = text.split().
  • Build a set from the words to find the unique ones, and print how many there are with len().
  • Make two sets of letters, vowels = {"a", "e", "i", "o", "u"} and a set of the letters actually used, then use & to find which vowels appear.
  • Write a function that returns a tuple (total_words, unique_words) and unpack it when you call it.

When you're done, see how immutable and mutable data behave differently inside error handling with try/except, where attempting an illegal operation is exactly the kind of thing you'll learn to catch safely.

Quick quiz

Test yourself and earn XP

What is the key difference between a tuple and a list?

What does a, b = (1, 2) do?

What does set([1, 2, 2, 3, 3, 3]) produce?

Which operator finds items present in BOTH sets a and b?

Why might you choose a set over a list to check if an item is present?

FAQ

Use a tuple when the collection should never change once created — coordinates like (x, y), a date as (year, month, day), or a fixed pair of related values. Because tuples are immutable, they signal to other programmers 'this data is constant', they can be used as dictionary keys (lists cannot), and they are slightly more memory-efficient. Use a list when you genuinely need to add, remove, or reorder items.

No. Sets are unordered, so you cannot index into them with set[0] and you should not rely on the order items appear when you print or loop over them. What sets give you in return is guaranteed uniqueness and very fast checks for whether a value is present. If order matters, use a list or a tuple; if uniqueness and fast lookup matter, reach for a set.