Chapters
Python114 chapters

CollectionsChapter 40 of 114

Set Methods

Adding, removing, and the four ways to compare two sets.

Adding and removing

Python
tags = {"python"}

tags.add("tutorial")
tags.update(["free", "python"])
print(sorted(tags))

tags.discard("missing")
tags.remove("free")
print(sorted(tags))
print(len(tags))

Output

['free', 'python', 'tutorial']
['python', 'tutorial']
2

remove() raises KeyError when the item is absent; discard() does not. Choose by whether absence is a problem.

Python
tags = {"a"}

try:
    tags.remove("b")
except KeyError:
    print("remove raises")

tags.discard("b")
print("discard does not")

Output

remove raises
discard does not

pop takes an arbitrary item

A set has no order, so there is no "first":

Python
numbers = {1, 2, 3}
taken = numbers.pop()

print(taken in {1, 2, 3})
print(len(numbers))

Output

True
2

Never rely on which item you get.

The four comparisons

Python
a = {1, 2, 3}
b = {3, 4}

print(sorted(a | b))
print(sorted(a & b))
print(sorted(a - b))
print(sorted(a ^ b))

Output

[1, 2, 3, 4]
[3]
[1, 2]
[1, 2, 4]
OperatorMethodGives
`\`unionin either
&intersectionin both
-differencein the first only
^symmetric_differencein one but not both

The methods accept any iterable; the operators need a set on both sides:

Python
a = {1, 2}
print(sorted(a.union([3])))

try:
    a | [3]
except TypeError:
    print("the operator needs a set")

Output

[1, 2, 3]
the operator needs a set

In-place versions

Each comparison has a method that changes the set rather than returning a new one:

Python
a = {1, 2, 3}
a.intersection_update({2, 3, 4})
print(sorted(a))

b = {1, 2, 3}
b.difference_update({1})
print(sorted(b))

Output

[2, 3]
[2, 3]

Testing relationships

Python
print({1, 2} <= {1, 2, 3})
print({1, 2, 3} >= {1, 2})
print({1, 2} < {1, 2})
print({1}.isdisjoint({2, 3}))

Output

True
True
False
True

<= is subset and < is proper subset, so a set is not a proper subset of itself.

frozenset

An immutable set. Because it cannot change, it hashes, so it can go inside another set or be a dictionary key:

Python
pair = frozenset({1, 2})
print(sorted(pair))

lookup = {frozenset({1, 2}): "the first pair"}
print(lookup[frozenset({2, 1})])

try:
    {{1, 2}}
except TypeError:
    print("a normal set cannot go inside a set")

Output

[1, 2]
the first pair
a normal set cannot go inside a set

Note the lookup worked with the items in the other order. A set has no order, so the two are the same key.

Test yourself

2 questions

What is the difference between remove() and discard()?

Show the answer

remove raises KeyError when the item is absent; discard does not — Choose by whether the item being absent is a problem worth hearing about.

Why can a frozenset go inside a set when a normal set cannot?

Show the answer

It cannot change, so it hashes — The same rule as dictionary keys: a hash must not change while the object is stored.

Next chapter

Dict and Set Comprehensions

Build a dictionary or a set in one line, the same way you build a list.