Learn / Beginner / Lesson 7

Tuples and sets

9 min Tested on Python 3.15Updated By
In short

A tuple is an ordered collection that can't be changed, written with round brackets: (52.5, 4.3). A set is an unordered collection of unique values, written with curly brackets: {"a", "b"}. Use tuples for fixed records and sets to remove duplicates or compare groups.

Tuples: fixed records

Python
point = (3, 4)
brussels = ("Brussels", 50.85, 4.35)
print(point[0])
print(len(brussels))

city, lat, lon = brussels   # unpacking
print(f"{city} is at {lat}, {lon}")
Output
3
3
Brussels is at 50.85, 4.35

Tuples are perfect when the values belong together and shouldn't change: coordinates, a date, a row from a database. Unpacking gives each value a name in one line.

Python
point = (3, 4)
try:
    point[0] = 10
except TypeError as err:
    print("Error:", err)
Output
Error: 'tuple' object does not support item assignment

Functions can return tuples

Python
numbers = [4, 9, 1, 7]
lowest, highest = min(numbers), max(numbers)
print(lowest, highest)

quotient, remainder = divmod(17, 5)
print(quotient, remainder)
Output
1 9
3 2

Sets: unique values

Python
visits = ["anna", "ben", "anna", "cara", "ben"]
unique = set(visits)
print(len(unique))
print(sorted(unique))

unique.add("dev")
unique.discard("ben")
print("ben" in unique)
Output
3
['anna', 'ben', 'cara']
False

Sets have no order and no positions, so unique[0] doesn't work. Checking x in a_set is very fast, even with millions of items.

Comparing groups

Python
python_devs = {"anna", "ben", "cara"}
ai_devs = {"ben", "cara", "dev"}

print(sorted(python_devs & ai_devs))   # in both
print(sorted(python_devs | ai_devs))   # in either
print(sorted(python_devs - ai_devs))   # only in the first
Output
['ben', 'cara']
['anna', 'ben', 'cara', 'dev']
['anna']

Which one should I use?

TypeOrderedChangeableDuplicatesTypical use
list []YesYesYesA collection that grows or changes
tuple ()YesNoYesA fixed record, e.g. coordinates
set {}NoYesNoUnique values, fast lookups

Practice

Two teams worked on a project. team_a = ["ana", "raj", "li", "raj"] and team_b = ["li", "tom", "ana"]. Print, as sorted lists: everyone who worked on it (no duplicates), then the people in both teams.

Expected output:
['ana', 'li', 'raj', 'tom']
['ana', 'li']
Your code

Quick check

1. What does len({1, 1, 2, 2, 3}) give?

2. Which creates an empty set?

3. Why choose a tuple over a list?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →