02 / COLLECTIONS AND DECISIONS · LESSON 08

Tuples, sets, and membership

Represent a fixed pair and compare expected and observed names.

11 min · learn at your pace

Choose a collection for its meaning

A tuple is an ordered collection whose entries cannot be reassigned: ("web-01", 443) can describe a hostname and a port. Unpacking gives each part a name: host, port = endpoint. A one-item tuple needs a trailing comma, such as ("web-01",).

A set contains unique, hashable values. set(observed) removes repeated names, and name in known_hosts asks a membership question. A set has no meaningful position: do not index it or rely on its printed order. Empty braces create a dictionary; use set() for an empty set.

Compare collections

Set difference answers “Which expected names are missing?” with expected - observed. Intersection (&) finds names in both collections; union (|) combines them. These operations avoid a growing list of manual comparisons.

A set is useful for presence checks, but it loses duplicate counts. Keep the original list if repeated records matter. Here the values are supplied names and a fictional endpoint; creating this tuple does not open a network connection.

Try an example.py
endpoint = ("web-01", 443)
host, port = endpoint
seen = set(["web-01", "web-01", "db-01"])
print(host in seen, port)
YOUR TURN

Put it into practice.

Create endpoint as the tuple ("web", 443). From observed = ["web", "web", "db"], create unique_hosts as a set. With expected = {"web", "db", "dns"}, create missing_hosts and a Boolean web_present.

See an explained solution
One way to solve it.py
endpoint = ("web", 443)
observed = ["web", "web", "db"]
expected = {"web", "db", "dns"}
unique_hosts = set(observed)
missing_hosts = expected - unique_hosts
web_present = "web" in unique_hosts
print(sorted(missing_hosts))

The tuple keeps the two endpoint values together. Set difference leaves dns because it is expected but was never observed.