Mutate Python Sets with add, update and discard
Core idea
s.add(value) inserts one member, while s.update(values) adds members from an iterable such as a list. s.remove(value) deletes a member but raises KeyError if absent; s.discard(value) does nothing when absent. s.clear() empties the set. These mutators return None. Use union when a new set is needed instead.
labels = {"A"}labels.add("B")labels.update(["B", "C"])print(sorted(labels))Repeated additions do not create duplicates.
Remove and discard
labels = {"A", "B"}labels.remove("A")labels.discard("Z")print(sorted(labels))labels.clear()print(len(labels))An absent Z is harmless with discard; clear removes all remaining members.
Observe in-place updates
a = {1}alias = aprint(a.add(2))new = a | {3}print(sorted(alias))print(sorted(new))The alias sees the mutation; union makes a separate set.
Common mistake
Do not write s = s.add(3) because that replaces the name with None. Also avoid relying on which member s.pop() removes; the choice is arbitrary, and an empty set raises KeyError.
Practice
Maintain a set of active labels: add a batch, discard a possibly absent label and display the remaining labels in sorted order.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Set mutation
Check your understanding of set mutation.
What is printed?
s = {1}print(s.add(2))What is printed?
s = {1}s.discard(2)print(sorted(s))What happens?
s = {1}s.remove(2)Which creates a new set without modifying s?