Python for beginners · Lesson 11 of 15

Tuples and sets

Use tuples for fixed groups of values and unpack them into variables; use sets to remove duplicates and compare groups.

About 14 minutes · code runs in your browser, nothing to install

Lists are not the only way to keep values together. A tuple is like a list that cannot be changed, and a set is a collection without duplicates and without order. Both are handy in everyday code.

Tuples

A tuple is written with round brackets. Indexing, slicing, len() and in work just as with lists, but you cannot add, remove or replace items: trying point[0] = 10 stops the program with a TypeError. That makes tuples a good fit for values that belong together and should stay fixed, like coordinates or a date.

Pythoneditable
point = (3, 5)
print(point)
print(point[0])
print(len(point))
colors = ("red", "green", "blue")
print("green" in colors)
single = (7,)
print(type(single))
print(type((7)))
Output
(3, 5)
3
2
True
<class 'tuple'>
<class 'int'>

A tuple with one item needs a trailing comma; (7) on its own is just the number 7 in brackets.

Unpacking

Unpacking puts the items of a tuple into separate variables in one line. The number of names on the left must match the number of items. It also gives you a neat way to swap two variables.

Pythoneditable
city, country = ("Lima", "Peru")
print(city)
print(country)
a = 1
b = 2
a, b = b, a
print(a, b)
Output
Lima
Peru
2 1

A list of tuples is a simple table. Unpacking right in the for line gives each column a name; this is what you already did with enumerate() in for loops: repeat for every item.

Pythoneditable
scores = [("Lena", 82), ("Omar", 95), ("Yuki", 78)]
for name, score in scores:
    print(f"{name}: {score}")
Output
Lena: 82
Omar: 95
Yuki: 78

Sets

A set keeps each value only once. Turning a list into a set with set() is the quickest way to remove duplicates. set.add() puts a new value in (adding one that is already there does nothing), and in checks membership very quickly.

Pythoneditable
visits = ["Rome", "Paris", "Rome", "Oslo", "Paris", "Rome"]
unique = set(visits)
print(len(unique))
print(sorted(unique))
unique.add("Lima")
unique.add("Rome")
print(sorted(unique))
print("Oslo" in unique)
Output
3
['Oslo', 'Paris', 'Rome']
['Lima', 'Oslo', 'Paris', 'Rome']
True
Watch out: Sets have no order, and a set of strings may print in a different order each time the program runs. Use sorted() whenever you show a set. Also note: {} creates an empty dictionary; an empty set is set().

Comparing groups

Sets can be combined like in maths: & gives the values in both sets (intersection), | the values in either (union) and - the values in the first but not the second (difference).

Pythoneditable
python_club = {"Ana", "Ben", "Chloe", "Dev"}
chess_club = {"Ben", "Dev", "Eva"}
print("Both:", sorted(python_club & chess_club))
print("Either:", sorted(python_club | chess_club))
print("Only Python:", sorted(python_club - chess_club))
Output
Both: ['Ben', 'Dev']
Either: ['Ana', 'Ben', 'Chloe', 'Dev', 'Eva']
Only Python: ['Ana', 'Chloe']

✎ Exercise

Two lists hold the guests of a Friday and a Saturday party. Print Both nights: followed by a sorted list of the guests who came on both nights, then print Different guests: followed by how many different people came in total.

Hint: Turn both lists into sets, then use & for the people in both and | for everyone.

Your codewrite your answer, then Run
friday = ["Mia", "Leo", "Sara", "Tom"]
saturday = ["Leo", "Nina", "Tom", "Ivan"]
# your code here

Expected output:

Both nights: ['Leo', 'Tom']
Different guests: 6
Show a solution
Solutioneditable
friday = ["Mia", "Leo", "Sara", "Tom"]
saturday = ["Leo", "Nina", "Tom", "Ivan"]
both = set(friday) & set(saturday)
everyone = set(friday) | set(saturday)
print("Both nights:", sorted(both))
print("Different guests:", len(everyone))
Output
Both nights: ['Leo', 'Tom']
Different guests: 6

Check yourself

1. Which of these can you change after creating it?

2. What is len(set([1, 1, 2, 2, 2]))?

3. How do you create an empty set?

Spotted a mistake on this page? Tell us