Python has four built-in collection types. You already know lists for ordered, changeable sequences and dictionaries for labelled data. This lesson covers the other two: tuples and sets.
A tuple is like a list that can never change. Once created, its items are fixed. That sounds limiting, but it's exactly what you want for values that belong together and shouldn't be edited by accident, such as a pair of map coordinates, an RGB colour or the year, month and day of a date.
A set is an unordered collection of unique items. Adding the same value twice has no effect, which makes sets perfect for removing duplicates and for questions such as "which students are in both clubs?". By the end of the lesson you'll know how to use both and, more importantly, how to pick the right collection for a job.
Creating and using tuples
Write a tuple with round brackets and commas:
point = (3, 7)
colour = (255, 165, 0)
print(point[0]) # 3
print(len(colour)) # 3Tuples support indexing, slicing, len(), in and loops, just like lists. What they don't support is change: there's no append(), and point[0] = 5 raises a TypeError.
It's actually the comma that makes a tuple, not the brackets. A tuple with one item therefore needs a trailing comma: single = ("red",). Without the comma, ("red") is just a string in brackets.
Unpacking
Unpacking assigns each item of a tuple to its own variable in one line:
x, y = point
name, age, city = ("Leo", 15, "Rome")The number of variables must match the number of items. Unpacking gives Python some of its neatest tricks. You can swap two variables without a temporary one, a, b = b, a, and a function can return several values at once by returning a tuple:
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([4, 9, 1])Star unpacking and tuple methods
When you don't know exactly how many items there will be, put a * before one variable to collect "the rest" into a list:
first, *middle, last = (10, 20, 30, 40, 50)
print(first) # 10
print(middle) # [20, 30, 40]
print(last) # 50Because tuples can't change, they have only two methods: count(value) and index(value). Everything else you do with a tuple uses general tools such as len(), in, sorted() and slicing.
A tuple is immutable, but the objects inside it might not be. In t = ([1, 2], "x") you can't replace t[0], yet t[0].append(3) works because the list itself is mutable. Keep tuples to simple values if you want them to stay truly fixed.
Sets: unique and unordered
Create a set with curly braces, or turn another collection into a set with set():
tags = {"python", "web", "python"}
print(tags) # {'python', 'web'}
unique = set([3, 1, 3, 2, 1]) # {1, 2, 3}
empty = set() # {} would make an empty dict- Duplicates are dropped automatically.
- Sets have no order and no indexes, so
tags[0]is an error. - Add items with
add(), remove them withremove()(error if missing) ordiscard()(no error). - Checking membership with
inis extremely fast, even for millions of items.
Set operations
Sets come with the operations you may remember from maths lessons:
| Operator | Method | Result |
|---|---|---|
a | b | a.union(b) | Items in either set |
a & b | a.intersection(b) | Items in both sets |
a - b | a.difference(b) | Items in a but not in b |
a ^ b | a.symmetric_difference(b) | Items in exactly one of them |
These answer real questions in a single line: which customers bought both products, which emails are new since last week, or which required fields are missing from a form.
Frozen sets and set comparisons
Sets can also be compared with each other. a <= b (or a.issubset(b)) asks whether every item of a is also in b, which answers questions like "has the user filled in every required field?":
required = {"name", "email"}
submitted = {"name", "email", "phone"}
print(required <= submitted) # TrueA normal set is mutable, so it can't be a dictionary key or an item in another set. A frozenset is the immutable version: frozenset({"a", "b"}). It supports every set operation that doesn't change it, such as | and &.
Python Tuples and Sets Syntax
Tuples and sets
t = (1, 2, 3)
a, b, c = t # unpacking
one = (5,) # one-item tuple
s = {1, 2, 3}
s.add(4)
s.discard(10)
s1 | s2 s1 & s2 s1 - s2Python Tuples and Sets Summary
- Tuples are ordered and immutable:
(1, 2); a one-item tuple needs a comma. - Unpacking assigns tuple items to variables:
x, y = point. - Functions can return several values as a tuple.
- Sets hold unique, unordered items;
set()makes an empty set. |,&,-and^give union, intersection, difference and symmetric difference.
Python Tuples and Sets Examples
Each example shows the code, the output it produces and what each part does.
Coordinates and swapping
start = (2, 5)
end = (8, 1)
x1, y1 = start
x2, y2 = end
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
print(f"Distance: {distance:.2f}")
a, b = "left", "right"
a, b = b, a
print(a, b)Distance: 7.21
right leftLine-by-line explanation
- Lines 1 to 2Each point is a fixed pair of numbers, so a tuple fits well.
- Lines 4 to 5Unpack each tuple into separate x and y variables.
- Line 6Pythagoras: the square root is the same as raising to the power 0.5.
- Line 10Swap two variables in one line using tuple unpacking.
Removing duplicates
visits = ["home", "about", "home", "shop", "about", "home"]
unique_pages = set(visits)
print(len(visits), "visits to", len(unique_pages), "pages")
print(sorted(unique_pages))
seen = []
for page in visits:
if page not in seen:
seen.append(page)
print(seen)6 visits to 3 pages
['about', 'home', 'shop']
['home', 'about', 'shop']Line-by-line explanation
- Line 3Converting to a set drops the repeats.
- Line 5sorted() turns the set into a sorted list for tidy output.
- Lines 7 to 10If you need to keep the original order, build a list and skip items already seen.
Comparing two clubs
chess = {"Ana", "Ben", "Cleo", "Dev"}
coding = {"Ben", "Dev", "Ema", "Finn"}
print("Both clubs:", sorted(chess & coding))
print("Either club:", len(chess | coding), "students")
print("Chess only:", sorted(chess - coding))
print("Just one club:", sorted(chess ^ coding))Both clubs: ['Ben', 'Dev']
Either club: 6 students
Chess only: ['Ana', 'Cleo']
Just one club: ['Ana', 'Cleo', 'Ema', 'Finn']Line-by-line explanation
- Line 4& keeps students who appear in both sets.
- Line 5| combines both sets; Ben and Dev are only counted once.
- Line 6- removes everyone who is also in the coding club.
- Line 7^ keeps students in exactly one of the clubs.
Common Python Tuples and Sets Mistakes
Forgetting the comma in a one-item tuple
sizes = ("large")
print(type(sizes)) # <class 'str'>sizes = ("large",)
print(type(sizes)) # <class 'tuple'>Creating an empty set with {}
seen = {}
seen.add("home") # AttributeError: 'dict' object has no attribute 'add'seen = set()
seen.add("home")Indexing a set
colours = {"red", "green"}
print(colours[0]) # TypeErrorcolours = {"red", "green"}
for c in sorted(colours):
print(c)Sets have no positions. Loop over them, or convert to a sorted list first.
Python Tuples and Sets in Real Projects
Tuples and sets in real programs
Database libraries often return each row as a tuple, because a row from a query shouldn't be edited by accident. Mapping code passes around (latitude, longitude) tuples. Sets appear whenever uniqueness matters: the tags on a blog post, the IDs of users who have already received an email, or the words a spell checker already knows.
Python Tuples and Sets FAQ
What is the difference between a list and a tuple in Python?
A list is mutable: you can add, remove and change items. A tuple is immutable: its items are fixed once it is created. Use a tuple for a fixed group of related values, such as coordinates or a returned pair, and a list for a collection that grows or changes. Tuples can also be dictionary keys, while lists can't.
Are tuples faster than lists?
Tuples are slightly smaller in memory and a little quicker to create, because Python knows they won't change. The difference rarely matters in everyday programs. Choose based on meaning (fixed or changing) rather than speed.
Does a Python set keep items in the order I added them?
No. Sets are unordered, and the order you see when printing can differ between runs and Python versions. If you need unique items in insertion order, use dict.fromkeys(items), and if you need them sorted, use sorted(my_set).
Can a set contain lists or dictionaries?
No. Set items must be hashable, which means immutable values such as numbers, strings, tuples and frozensets. Trying to add a list raises TypeError: unhashable type: 'list'. Convert the list to a tuple first if you need to store it in a set.
When should I use a set instead of a list?
Use a set when every item should appear only once, or when you mostly ask "is this item in the collection?". Membership checks on a set stay fast even with millions of items, while a list has to be scanned item by item.
Python Tuples and Sets Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the code so it unpacks the tuple into two variables.
size = (1920, 1080)
, height = size
What does this print?
nums = {4, 2, 4, 2, 4}
print(len(nums))
What does this print?
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a - b), sorted(a & b))
Which line creates an empty set?
Which collection best stores a GPS position that must never be edited?
Python Tuples and Sets Quiz
5 questions to check what you learned.
What makes a tuple different from a list?
- Tuples can only hold numbers
- Tuples are unordered
- Tuples can't be changed after they're created
- Tuples use square brackets
What happens if you add a value that's already in a set?
- An error
- It's added twice
- The old value is replaced
- Nothing, sets keep only unique values
What does
a, b = b, ado?- Swaps the values of a and b
- Raises an error
- Makes both variables equal to a
- Creates a list
Which operator gives the items found in both sets?
- |
- &
- -
- +
Why is
("red")not a tuple?- It's the comma that makes a tuple; this is just a string in brackets
- Tuples can't contain strings
- Tuples need at least three items
- It needs square brackets