LESSON · 1 OF 5

Creating sets

Creating sets

A set is an unordered collection of unique values. Two things make it different from a list: it never holds duplicates, and it doesn't keep any order. Write one with curly braces:

python
ports = {80, 443, 8080}

Duplicates disappear

If you put the same value in twice, the set keeps just one copy. This is the defining behavior:

python
ports = {80, 443, 80, 8080, 443}
print(ports)   # {80, 443, 8080}

No order, no indexing

A set doesn't track position, so there's no first or last item and you can't index it. This fails:

python
ports[0]
# TypeError: 'set' object is not subscriptable

When you print a set the items may come out in any order. If you need order or indexing, you want a list, not a set.

Making a set from a list

Passing a list to set() builds a set from its values, dropping any duplicates along the way. This is the most common way you'll create a set in practice:

python
hosts = ["web-01", "web-02", "web-01"]
unique = set(hosts)
print(unique)   # {'web-01', 'web-02'}

Membership and size

The in operator and len work just like they do on a list, and in on a set is very fast even when the set is large:

python
print("web-01" in unique)   # True
print(len(unique))          # 2

The empty set gotcha

Empty braces {} make an empty dictionary, not an empty set. For an empty set you must call set():

python
empty = set()
Spin up a fresh environment and practice live.
python-devops · fresh machine · ready in under a minute