Sub topic 5
Adding and Removing Elements
This chapter assumes you can create sets, know that set elements must be hashable, and understand the difference between mutable and immutable objects. A set is mutable, so you can change it after you create it. A frozenset is not mutable, and it is covered in a later chapter.
Adding elements
add() inserts one element. If the element is already present, nothing happens and no error is raised. This follows from the rule that a set holds each value at most once.
tags = {"python", "sets"}
tags.add("hash")
tags.add("python") # already present, no effect
print(sorted(tags)) # ['hash', 'python', 'sets']add() takes exactly one argument and returns None. To add several elements at once, use update(). That method is covered in the chapter on in-place operations.
The element you add must be hashable. Adding a list raises TypeError, as it does in a set literal.
s = {1, 2}
try:
s.add([3, 4])
except TypeError as e:
print(e) # unhashable type: 'list'
s.add((3, 4)) # a tuple works
print(len(s)) # 3Removing elements
Python offers three ways to remove an element from a set, plus clear(). They differ in what they do when the element is missing.
| Method | Removes | If the element is missing |
|---|---|---|
| `remove(x)` | The element `x` | Raises `KeyError` |
| `discard(x)` | The element `x` | Does nothing |
| `pop()` | An arbitrary element, which it returns | Raises `KeyError` if the set is empty |
| `clear()` | Every element | Does nothing |
s = {1, 2}
s.add(3)
s.discard(10) # no error if the element is missing
print(sorted(s)) # [1, 2, 3]
try:
s.remove(10) # raises KeyError if the element is missing
except KeyError:
print("10 is not in the set")
item = s.pop() # removes and returns an arbitrary element
print(item in {1, 2, 3}) # TrueChoosing between remove and discard
Use remove() when the element should be there and its absence means a bug elsewhere in your program. The KeyError surfaces the problem at once. Use discard() when you only want the element gone and do not care whether it was there.
def revoke(active_users, user):
active_users.discard(user) # revoking twice is harmlessWhy pop is arbitrary
pop() does not take the first or last element, because a set has no first or last. It returns whichever element the internal hash table yields first. For a small set of integers this can look like the smallest value, but that is an implementation detail and you must not rely on it. For strings the choice can differ between runs, because string hashes are randomized per process.
queue = {"a", "b", "c"}
while queue:
work = queue.pop()
print("processing", work) # order is not guaranteedUse pop() when you want to drain a set in any order. If order matters, use a list or a collections.deque.
s = {1, 2, 3, 4}
for x in list(s): # iterate over a snapshot
if x % 2 == 0:
s.discard(x)
print(sorted(s)) # [1, 3]How add and remove relate to membership
Every one of these operations hashes the element first. Because a set is a hash table, add, remove, and discard take roughly constant time on average. A list remove() must scan the list, which takes time proportional to its length.
Common errors
- Writing
s.add(1, 2).add()accepts one argument, so this raisesTypeError. Pass a tuple,s.add((1, 2)), to store a pair, or useupdate()to add each value. - Assigning the result:
s = s.add(5)setsstoNone, becauseadd()changes the set in place and returns nothing. - Calling
pop()on an empty set, which raisesKeyError. Test withif s:first. - Passing an index to
pop(). Sets have no positions, sos.pop(0)raisesTypeError.
Exercise
A set seen = {"a", "b"} is given. You run seen.remove("c") and get a KeyError. Which single method call would let the same step run without an error, and what does it do when "c" is absent?
Show answer
Use seen.discard("c"). It removes "c" if present and does nothing if it is absent, so no KeyError is raised.
Exercise
What does this code print, and why? s = {1, 2, 3}; r = s.add(4); print(r, len(s))
Show answer
It prints None 4. add() modifies the set in place and returns None, so r is None, while the set now holds four elements.