Chapter 9

Tuples and Sets

A list is not the only collection Python offers. Tuples suit fixed sequences, and sets suit the moments when uniqueness and membership are what matter.

Chapter 9, Tuples and Sets

What you will learn

  • Create and unpack tuples.
  • Understand tuple immutability.
  • Use sets for unique values and fast membership checks.
  • Choose an appropriate collection type.

The code from this chapter

Type these programs yourself. The predictions below are the exercises; the explanations are in the book.

9.1 Tuples

TPRM Lab 9.1: Unpack a Tuple

Type this into a file, predict the output, then run it.

Python
point = (3, 4)
x, y = point

print(x)
print(y)

9.2 Sets

Type this into a file, predict the output, then run it.

Python
expected = {"Ana", "Leo", "Mia"}
arrived = {"Leo", "Mia", "Sam"}

print(expected & arrived)
print(expected - arrived)
print(arrived - expected)

TPRM Lab 9.2: Remove Duplicates

Type this into a file, predict the output, then run it.

Python
names = ["Ana", "Leo", "Ana", "Mia", "Leo"]
unique_names = set(names)

print(unique_names)
print(len(unique_names))

Back to Python the TPRM Way