Sub topic 8
In-place operations and update methods
This chapter assumes you know the set operators |, &, - and ^, and that you understand mutable and immutable objects. The earlier operators build a new set. The in-place forms change an existing set instead.
Operators and methods that modify a set
Each set operation has an in-place version. The table lists them.
| New set | In-place operator | In-place method | Result | Column | Column |
|---|---|---|---|---|---|
| `a \ | b` | `a \ | = b` | `a.update(b)` | Adds every element of `b` to `a` |
| `a & b` | `a &= b` | `a.intersection_update(b)` | Keeps only elements found in both | ||
| `a - b` | `a -= b` | `a.difference_update(b)` | Removes elements that are in `b` | ||
| `a ^ b` | `a ^= b` | `a.symmetric_difference_update(b)` | Keeps elements found in exactly one of the two |
The in-place forms change a and return None. They never create a second set for the result.
s = {1, 2, 3}
s.update([3, 4], (5, 6)) # update accepts several iterables
print(sorted(s)) # [1, 2, 3, 4, 5, 6]
s |= {7}
print(sorted(s)) # [1, 2, 3, 4, 5, 6, 7]Methods accept any iterable, operators do not
The method forms take any iterable: lists, tuples, strings, dict keys, generators. The operator forms require a set or frozenset on the right-hand side.
s = {1, 2}
try:
s |= [3] # operator needs a set
except TypeError:
print("operator needs a set")
s.update([3]) # method accepts a list
print(sorted(s)) # [1, 2, 3]Use the method when your data is not already a set. This also avoids building a temporary set just to merge it.
Shrinking and toggling
The other three update methods work the same way.
base = {1, 2, 3, 4, 5}
base.intersection_update({2, 3, 4, 9})
print(sorted(base)) # [2, 3, 4]
base.difference_update([4])
print(sorted(base)) # [2, 3]
base.symmetric_difference_update({3, 10})
print(sorted(base)) # [2, 10]The last call removes 3, because both sets contain it, and adds 10, because only the argument contains it. This makes ^= a convenient way to toggle membership for several elements at once.
Aliasing: in-place changes are visible through every name
An in-place operation mutates the object. Every variable that refers to that object sees the change. The plain operator creates a new object and rebinds only one name.
a = {1, 2}
b = a # b is another name for the same set
a |= {3}
print(sorted(b)) # [1, 2, 3], b changed too
c = a
a = a | {4} # builds a new set and rebinds a
print(sorted(c)) # [1, 2, 3], c is unchanged
print(sorted(a)) # [1, 2, 3, 4]This matters when you pass a set to a function. A function that runs param |= extra changes the caller's set. A function that runs param = param | extra does not.
Frozensets are immutable, so |= on a frozenset falls back to the plain operator. It builds a new frozenset and rebinds the name.
f = frozenset({1})
g = f
f |= {2}
print(sorted(f)) # [1, 2]
print(sorted(g)) # [1], the original is untouchedCommon errors
- Assigning the result. The update methods return
None. Writings = s.update(items)replaces your set withNone. - Passing a non-set to an operator.
s &= [1, 2]raisesTypeError. Uses.intersection_update([1, 2]). - Passing a string by mistake.
s.update("abc")adds the characters'a','b'and'c', not the string"abc". To add one string, uses.add("abc")ors.update(["abc"]). - Unhashable items.
s.update([[1, 2]])raisesTypeError, because the inner list is not hashable. - Changing a set while looping over it. Adding or removing elements inside
for x in s:raisesRuntimeError: Set changed size during iteration. Loop overlist(s)or build the changes first and apply them afterwards.
s = {1, 2, 3, 4}
result = s.update([5])
print(result) # None
s.update("ab")
print(sorted(s, key=str)) # [1, 2, 3, 4, 5, 'a', 'b']
for x in list(s): # safe: iterates over a copy
if isinstance(x, str):
s.discard(x)
print(sorted(s)) # [1, 2, 3, 4, 5]Choosing between the forms
- Use the in-place form when you are accumulating into one set, such as collecting unique IDs in a loop, or when the caller expects its set to change.
- Use the plain operator when the original must stay intact, or when you want a frozenset-safe expression.
- Use the method form when the other value is not a set.
Exercise
A function receives seen = {1, 2, 3} and runs seen &= {2, 3, 4}. A second name backup = seen was created before the call. What do seen and backup contain afterwards? What would change if the function used seen = seen & {2, 3, 4} instead?
Show answer
With &=, the set object is changed in place, so both seen and backup contain {2, 3}. With seen = seen & {2, 3, 4}, a new set {2, 3} is built and bound to seen, while backup still refers to the original {1, 2, 3}.
Exercise
Why does s.update("hello") leave a set with 4 new elements rather than 1, and how would you add the single string "hello" instead?
Show answer
A string is an iterable of characters, so update adds 'h', 'e', 'l' and 'o'. The letter 'l' appears twice but is stored once, giving 4 elements. Use s.add("hello") or s.update(["hello"]) to add the whole string.