Sets

Modifying Python Sets

Creating a set is only the beginning. This lesson covers how to grow and shrink sets after creation: .add() inserts elements, .discard() removes them safely, and .clear() wipes everything. You will also see why .discard() is often safer than .remove().


Now that you can create sets and check membership, the next step is learning how to change them.

The .add() method inserts a single element into the set.

Python
Output

Adding a value that already exists has no effect. The set stays the same.

Python
Output

What will be the output?

Python

.remove() deletes an element from the set.

Python
Output

But if the element is missing, .remove() raises a KeyError and your program crashes:

Python

.discard() is the safe alternative. It also removes elements, but does nothing when the element is missing.

Python
Output

What will be the output?

Python

Two more useful methods: .pop() removes and returns an arbitrary element, and .clear() empties the entire set.

After .clear(), the set is empty.

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python