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.
Adding a value that already exists has no effect. The set stays the same.
What will be the output?
.remove() deletes an element from the set.
But if the element is missing, .remove() raises a KeyError and your program crashes:
.discard() is the safe alternative. It also removes elements, but does nothing when the element is missing.
What will be the output?
Two more useful methods: .pop() removes and returns an arbitrary element, and .clear() empties the entire set.
After .clear(), the set is empty.
What will be the output?
What will be the output?
What will be the output?
What will be the output?
What will be the output?