Sub topic 5
Adding and Removing Elements
Prerequisites
This chapter assumes you can create a set and test membership with in. It also assumes you know that set elements must be hashable and that mutable objects can change after you create them. Here you will learn the methods that change a set after creation: add, update, remove, discard, pop and clear. You will also learn which errors they raise and how to avoid the main trap, changing a set while looping over it.
Adding one element with add
set.add(x) inserts x if it is not already present. If an equal element exists, the call does nothing. The method changes the set in place and returns None.
s = {1, 2}
s.add(3)
s.add(3) # already present, no effect
print(sorted(s)) # [1, 2, 3]
result = s.add(4)
print(result) # NoneBecause add returns None, writing s = s.add(4) is a bug. It replaces your set with None.
Equal elements are not replaced
A set decides "already present" using hashing and equality. The values 1, 1.0 and True are equal and have the same hash, so they count as one element. The set keeps the object it already holds.
s = {1}
s.add(1.0)
s.add(True)
print(s) # {1}
print(len(s)) # 1This matters when you add values from mixed sources, such as numbers parsed from text and numbers computed in code. The first value stored decides which object stays in the set.
Elements must be hashable
add raises TypeError for an unhashable value such as a list, dict or another set. Convert it first. For a list, use a tuple. For a set, use a frozenset.
s = set()
s.add((1, 2)) # a tuple is hashable
s.add(frozenset({3, 4})) # a frozenset is hashable
try:
s.add([5, 6])
except TypeError as e:
print(e) # unhashable type: 'list'Adding many elements with update
set.update(*iterables) adds every element from each argument. The arguments can be any iterable: a list, a tuple, a string, a generator or another set. You can pass several at once.
s = {1}
s.update([2, 3], (3, 4), {5})
print(sorted(s)) # [1, 2, 3, 4, 5]A common mistake is passing a string when you meant to add the whole string. A string is an iterable of characters, so update adds each character.
tags = {"python"}
tags.update("sets") # adds 's', 'e', 't'
print(len(tags)) # 4
tags = {"python"}
tags.update(["sets"]) # adds the string "sets"
print(sorted(tags)) # ['python', 'sets']update is the method form of |=. The operator requires a set on the right, while the method accepts any iterable.
s = {1}
s.update([2, 3]) # works
try:
s |= [4, 5] # operator needs a set
except TypeError as e:
print("TypeError")
s |= {4, 5}
print(sorted(s)) # [1, 2, 3, 4, 5]Removing elements
Python has four ways to remove elements. They differ in what happens when the element is missing and in how you pick which element to remove.
remove and discard
Both take a specific element. remove raises KeyError if the element is absent. discard does nothing in that case.
s = {1, 2, 3}
s.discard(10) # silent, nothing to remove
s.discard(1)
print(sorted(s)) # [2, 3]
try:
s.remove(10)
except KeyError:
print("10 is not in the set")
s.remove(2)
print(sorted(s)) # [3]Use remove when a missing element means your program has a bug, because the error exposes it. Use discard when "make sure this is gone" is the whole intent.
pop
pop() removes one element and returns it. You cannot choose which one. The set has no defined order, so treat the result as arbitrary. Small integers may seem to come out in sorted order, but that is an implementation detail and not something to rely on.
Calling pop() on an empty set raises KeyError. That makes it a good fit for a "drain the work queue" loop that tests the set's truth value first. An empty set is falsy.
work = {"a", "b", "c"}
done = []
while work:
done.append(work.pop())
print(sorted(done)) # ['a', 'b', 'c']
try:
work.pop()
except KeyError as e:
print(e) # 'pop from an empty set'clear
clear() removes every element and keeps the same set object. This is different from rebinding the name to a new empty set. If other names refer to the same set, clear() empties it for all of them.
a = {1, 2, 3}
b = a # same object, not a copy
a.clear()
print(b) # set()
a = {1, 2, 3}
b = a
a = set() # rebinding: b still holds the old set
print(sorted(b)) # [1, 2, 3]Removing many elements
To remove several known elements, use difference_update or the -= operator. Elements that are not present are ignored, as with discard.
s = {1, 2, 3, 4, 5}
s.difference_update([1, 2, 99])
print(sorted(s)) # [3, 4, 5]
s -= {5}
print(sorted(s)) # [3, 4]Choosing a method
| Method | Takes | Missing element | Returns |
|---|---|---|---|
| `add(x)` | one element | not applicable | `None` |
| `update(*its)` | any iterables | not applicable | `None` |
| `remove(x)` | one element | raises `KeyError` | `None` |
| `discard(x)` | one element | does nothing | `None` |
| `pop()` | nothing | raises `KeyError` if set is empty | the removed element |
| `clear()` | nothing | not applicable | `None` |
Edge cases
Removing a set from a set of frozensets
add rejects a plain set as an element. The lookup methods remove, discard and in are more forgiving. If you give them a set, Python temporarily treats it as a frozenset for the lookup, so you can remove a stored frozenset without building one yourself.
groups = {frozenset({1, 2}), frozenset({3})}
print({1, 2} in groups) # True
groups.discard({1, 2})
print(len(groups)) # 1
try:
groups.add({9})
except TypeError as e:
print(e) # unhashable type: 'set'Mutable elements that change
Elements must be hashable, and hashable objects are normally immutable. If you store an object whose hash depends on mutable state, and then change that state, the set can no longer find it. Avoid this by only storing immutable values or by not mutating stored objects.
Changing a set while iterating
Do not add or remove elements from a set inside a loop over that same set. Python detects a size change and raises RuntimeError.
nums = {1, 2, 3, 4}
try:
for n in nums:
if n % 2 == 0:
nums.remove(n)
except RuntimeError as e:
print(e) # Set changed size during iterationThere are two safe fixes. Build a new set with a comprehension, or loop over a snapshot of the elements.
nums = {1, 2, 3, 4}
nums = {n for n in nums if n % 2} # keep odd numbers
print(sorted(nums)) # [1, 3]
nums = {1, 2, 3, 4}
for n in list(nums): # snapshot, so the loop is unaffected
if n % 2 == 0:
nums.remove(n)
print(sorted(nums)) # [1, 3]When the rule is simple, the comprehension is clearer. When removing needs side effects such as logging or cleanup, the snapshot loop is more direct.
Summary
addinserts one hashable element and returnsNone. Adding an equal element changes nothing.updateinserts every element from any iterables. Strings are split into characters.removeraisesKeyErrorfor a missing element, anddiscarddoes not.popremoves an arbitrary element and raisesKeyErroron an empty set.clearempties the existing object, and rebinding toset()does not.- Do not modify a set during iteration. Use a comprehension or iterate over
list(s).
Exercise
You have seen = {"a", "b"} and run seen = seen.add("c"). Then you call len(seen). What happens, and what is the correct code?
Show answer
add returns None, so seen becomes None and len(seen) raises TypeError: object of type 'NoneType' has no len(). The correct code is just seen.add("c"), which modifies the set in place without assignment.
Exercise
Write code that removes every string shorter than 3 characters from words = {"a", "to", "cat", "tree", "it"} without raising RuntimeError. Give one version that builds a new set and one that edits the set in place.
Show answer
New set: words = {w for w in words if len(w) >= 3}. In place: for w in list(words): followed by if len(w) < 3: words.remove(w) on the next line. Both leave {"cat", "tree"}. Looping over list(words) iterates a snapshot, so removing from words does not change the collection being iterated.