Python language basics 51: removing elements from a set
September 27, 2015 Leave a comment
Introduction
In the previous post we discussed how to add new elements to an existing set. You can use the add method to add a single new element. The update function helps you insert multiple values at once. Both methods gracefully ignore duplicates, the set is guaranteed to only hold unique values.
In this post we’ll look at the opposite operation, i.e. how to remove objects.
Removing objects from a set
Consider the following set:
capitals = {"Stockholm", "Budapest", "Helsinki", "Copenhagen", "Oslo", "Paris"}
Let’s say you want to remove Oslo. The remove method is a straightforward solution:
capitals.remove("Oslo")
‘capitals’ will become…
{‘Budapest’, ‘Paris’, ‘Copenhagen’, ‘Helsinki’, ‘Stockholm’}
…as expected.
Note, however, that the function results in an error if you try to remove an object which is not in the set:
capitals.remove("Washington")
This will result in a key error:
KeyError: ‘Washington’
We’ll see later on in the course how to handle such errors in code.
There’s another function called ‘discard’ which works in a similar way but ignores objects that do not exist in the set:
capitals.discard("Washington")
The above call will simply execute without raising the same error as above.
In general you can use the ‘remove’ method if you want to know whether the removal was successful, i.e. the element existed in the set to begin with. Use ‘discard’ if you don’t care: remove the element if it exists otherwise just continue.
In the next post we’ll discuss some useful methods related to set algebra.
Read all Python-related posts on this blog here.