Sub topic 8
In-place operations and update methods
This chapter assumes you know how to create sets, that their elements must be hashable, and how union, intersection, difference and symmetric difference work as operators. It covers the in-place forms of those operations, which change a set instead of building a new one.
Two ways to combine sets
The operators |, &, - and ^ return a new set and leave both operands alone. Each has an in-place counterpart that modifies the left-hand set.
| Operation | New set | In-place operator | In-place method | Column | Column |
|---|---|---|---|---|---|
| Union | `a \ | b` | `a \ | = b` | `a.update(b)` |
| Intersection | `a & b` | `a &= b` | `a.intersection_update(b)` | ||
| Difference | `a - b` | `a -= b` | `a.difference_update(b)` | ||
| Symmetric difference | `a ^ b` | `a ^= b` | `a.symmetric_difference_update(b)` |
The in-place forms save work when you grow or shrink a set step by step. total = total | extra copies every element of total into a fresh set. total |= extra only adds the new elements to the existing set.
update: adding many elements
update adds every element of its arguments. It accepts any number of iterables, not only sets.
a = {1, 2, 3}
a.update([3, 4], (5,), range(6, 8))
print(sorted(a)) # [1, 2, 3, 4, 5, 6, 7]
result = a.update([10])
print(result) # NoneLike list.append and list.sort, the in-place methods return None. A line such as a = a.update(x) replaces your set with None, and the failure shows up later.
update is the bulk version of add. Use add for one element and update for an iterable. The difference matters when the argument is a string:
tags = {"python"}
tags.add("sets")
tags.update("sets") # iterates the string, adding characters
print(sorted(tags)) # ['e', 'python', 's', 't', 'sets']update("sets") adds the characters s, e and t, because a string is an iterable of one-character strings. To add a whole string, use add, or pass a list: tags.update(["sets"]).
The other three update methods
The remaining methods follow the same pattern as the operators.
a = {1, 2, 3, 4}
a.intersection_update([2, 3, 9])
print(sorted(a)) # [2, 3]
b = {1, 2, 3, 4}
b.difference_update([2], {4})
print(sorted(b)) # [1, 3]
c = {1, 2, 3}
c.symmetric_difference_update({3, 4})
print(sorted(c)) # [1, 2, 4]intersection_updatekeeps only the elements found in every argument. Passing several arguments intersects all of them:a.intersection_update(b, c).difference_updateremoves every element found in any argument. Several arguments are allowed here too.symmetric_difference_updatetakes exactly one argument. Symmetric difference of more than two sets is not defined by a single call, so the method does not accept more.
Keep in mind that intersection_update can remove elements from the set. If the argument shares nothing with the set, the result is empty.
Operators versus methods
The operator forms require both sides to be sets (or frozensets). The method forms accept any iterable and convert it internally.
s = {1, 2}
s.update([3, 4]) # fine: a list is an iterable
print(sorted(s)) # [1, 2, 3, 4]
try:
s |= [5, 6] # operator form needs a set on the right
except TypeError:
print("TypeError: cannot |= a list")The restriction is deliberate. An operator that quietly accepts a list or a string would hide mistakes such as s |= "abc". The method name tells the reader that you mean to read the argument as a stream of elements. When your data is not already a set, prefer the method form. When both sides are sets, the operator form is shorter.
Aliasing: other names see the change
An in-place operation changes the object itself. Every variable bound to that object sees the change.
a = {1, 2}
b = a # b is another name for the same set
a |= {3}
print(sorted(b)) # [1, 2, 3]
c = a | {4} # the plain operator builds a new set
print(sorted(a)) # [1, 2, 3]
print(sorted(c)) # [1, 2, 3, 4]This causes real bugs when a set is passed into a function that uses -= or .update on its parameter. The caller's set changes. If a function should not modify its input, copy first:
def without_stopwords(words, stopwords):
result = set(words) # copy, so the caller's set is untouched
result -= stopwords
return result
original = {"the", "cat", "sat"}
print(sorted(without_stopwords(original, {"the"}))) # ['cat', 'sat']
print(sorted(original)) # ['cat', 'sat', 'the']set(words) works whether words is a set, a list or any other iterable. words.copy() would fail on a list, since lists have no copy method in this form that returns a set.
Frozensets and the augmented operators
A frozenset has no update, add or any other mutating method. Calling one raises AttributeError. The augmented operators still work on a frozenset variable, but they behave differently. When an object does not define the in-place version, Python falls back to the plain operator and rebinds the name to the result.
f = frozenset({1, 2})
g = f
f |= {3} # rebinds f to a new frozenset
print(sorted(f)) # [1, 2, 3]
print(sorted(g)) # [1, 2]
print(type(f).__name__) # frozensetHere g still holds the original, so there is no aliasing effect. The result also stays a frozenset: when you mix types in a plain operator, the type of the left operand wins. The same line with a set on the left would give a set.
The flow below summarizes what happens with x op= y.
Do not change a set while looping over it
Python checks the size of a set during iteration. If the size changes, the next step of the loop raises RuntimeError.
s = {1, 2, 3}
try:
for x in s:
s.add(x + 10)
except RuntimeError as e:
print(e) # Set changed size during iterationThis applies to add, remove, discard, pop and every in-place operation. Two safe patterns avoid it:
s = {1, 2, 3, 4, 5, 6}
# Pattern 1: iterate over a snapshot
for x in list(s):
if x % 2 == 0:
s.discard(x)
print(sorted(s)) # [1, 3, 5]
# Pattern 2: describe the change as a set, then apply it once
t = {1, 2, 3, 4, 5, 6}
evens = {x for x in t if x % 2 == 0}
t -= evens
print(sorted(t)) # [1, 3, 5]The second pattern is usually clearer and faster, because the removal happens in a single operation instead of one call per element.
Practical patterns
Narrowing down: intersecting many collections
Start from the first collection and shrink it with &= or intersection_update. This reads a list of tag lists and finds the tags that every list contains:
tag_lists = [["a", "b", "c"], ["b", "c", "d"], ["c", "b", "z"]]
common = set(tag_lists[0])
for tags in tag_lists[1:]:
common.intersection_update(tags)
if not common: # nothing left, so stop early
break
print(sorted(common)) # ['b', 'c']Because the method accepts any iterable, tags can stay a list. The early exit is worth having: once common is empty it cannot grow again.
Building up: collecting unique items
seen = set()
for line in ["x y", "y z", "z w"]:
seen.update(line.split())
print(sorted(seen)) # ['w', 'x', 'y', 'z']Cleaning up: removing a blocklist
users = {"ana", "bo", "cy", "dee"}
banned = ["bo", "dee", "unknown"]
users.difference_update(banned)
print(sorted(users)) # ['ana', 'cy']Names in banned that are not in users are ignored. That differs from remove, which raises KeyError for a missing element.
Toggling membership
symmetric_difference_update flips each listed element: present ones are removed and missing ones are added. This suits a feature-flag list or a "selected items" set where each click toggles.
selected = {"red", "green"}
selected ^= {"green", "blue"} # click green (off) and blue (on)
print(sorted(selected)) # ['blue', 'red']Common errors
- Assigning the result.
s = s.update(x)setsstoNone. Call the method on its own line. - Operator with a non-set.
s |= [1, 2]raisesTypeError. Uses.update([1, 2]). - Adding a string by mistake.
s.update("abc")adds three characters, not one string. - Surprising input mutation. Using
-=or.updateon a parameter changes the caller's set. Copy first when the function should be free of side effects. - Mutating during iteration. Iterate over
list(s)or build the change as a separate set. - Expecting a frozenset to change.
f |= xcreates a new object. Other names bound to the old frozenset do not see it.
Exercise
A function receives a set names and must return the set with all names starting with "_" removed, without changing the caller's set. Write the function body using an in-place operation, and say why you need a copy.
Show answer
def publicnames(names):
result = set(names)
result -= {n for n in result if n.startswith("")}
return result
The copy is needed because -= changes the object it is applied to. Without set(names), the caller's set would lose its private names too. The set of names to remove is built first, so the set is not modified while it is being iterated.
Exercise
Given a = {1, 2, 3} and b = a, what do a and b contain after a |= {4}? What do they contain if a and b are frozensets instead? Explain the difference.
Show answer
For sets, both a and b contain {1, 2, 3, 4}, because |= modifies the one shared object in place. For frozensets, a becomes a new frozenset {1, 2, 3, 4} and b still holds {1, 2, 3}, because a frozenset has no in-place union, so Python computes a | {4} and rebinds the name a.