Python Set Methods
Sets provide methods to add and remove items and to perform mathematical operations like union and intersection.
Adding and removing items
Although a set has no order, it is still changeable. Use add() to insert a single item and update() to add several items at once from another iterable. To take items out, discard() and remove() both delete a value, while pop() removes an arbitrary item and clear() empties the set entirely.
Add and remove
tags = {"python", "code"}
tags.add("tutorial")
tags.update(["beginner", "code"]) # code is ignored (already present)
print(tags)
tags.discard("beginner") # no error even if missing
tags.remove("tutorial") # KeyError if missing
print(tags)Set operations: union and intersection
Sets shine when comparing collections. union() returns all items that appear in either set, while intersection() returns only the items shared by both. Neither method changes the original sets; they produce a new set.
Union and intersection
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a.union(b)) # {1, 2, 3, 4, 5, 6}
print(a.intersection(b)) # {3, 4}
# The | and & operators do the same thing
print(a | b) # union
print(a & b) # intersectionDifference and symmetric difference
difference() returns items that are in the first set but not the second, and symmetric_difference() returns items found in exactly one of the two sets. These help you answer questions like "what changed?" between two groups.
Difference operations
morning = {"Ana", "Ben", "Cara"}
evening = {"Ben", "Cara", "Dan"}
print(morning.difference(evening)) # {'Ana'}
print(morning.symmetric_difference(evening)) # {'Ana', 'Dan'}Comparing sets
- issubset(): checks whether every item of one set is contained in another.
- issuperset(): checks whether a set contains all items of another.
- isdisjoint(): checks whether two sets share no items at all.
- union() and intersection() accept several sets at once, for example a.union(b, c).