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)
Note: remove() raises a KeyError if the item is not in the set, while discard() removes the item if present and does nothing otherwise. Prefer discard() when you are not certain the value exists.
MethodWhat it doesIf item is missing
add(x)Adds a single itemNot applicable
update(iterable)Adds many itemsNot applicable
discard(x)Removes an itemDoes nothing
remove(x)Removes an itemRaises KeyError
pop()Removes a random itemRaises KeyError if empty
clear()Removes all itemsNot applicable

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)               # intersection

Difference 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).
Note: Most set methods have an equivalent operator: union is |, intersection is &, difference is -, and symmetric difference is ^. The methods can take any iterable as an argument, while the operators require both operands to be sets.