## Set Operations

In mathematics, set operations include union, intersection, add, and remove. In Python, these are implemented as methods (for a complete

Figure 9.1: Creating a set list, see Figure 9.2, on the next page). Note that most operations create a new set: only add, remove, and clear modify the current set. The following program shows these methods in action:

>>> ten = set(range(10)) >>> lows = set([0, 1, 2, 3, 4]) >>> odds = set([1, 3, 5, 7, 9]) >>> lows.add(9) >>> lows set([0, 1, 2, 3, 4, 9])

>>> lows.difference(odds)

>>> lows.intersection(odds)

True

>>> lows.issuperset(odds) False

>>> lows.remove(0) >>> lows set([1, 2, 3, 4, 9])

>>> lows.symmetric_difference(odds)

Method add clear difference intersection issubset issuperset remove symmetric_difference

Purpose

Adds an element to a set Removes all elements from a set

Creates a set with elements from one set, but not the other

Creates a set with elements that are in both sets Asks are all of one set's elements contained in another?

Asks does one set contain all of another's elements? Removes an element from a set

Creates a set with elements that are in exactly one set Creates a set with elements that are in either set

lows.difference(odds)

lows.intersection(odds) lows.issubset(ten)

lows.issuperset(odds) lows.remove(O)

Result

False None lows.symmetric_difference(odds) set((0, 2, 4, 5, 7, 9))) lows.union(odds) set((0, 1, 2, 3, 4, 5, 7, 9)))

Figure 9.2: Set operations, where ten = set(range(10)), lows = set([0, 1, 2, 3, 4]), and odds = set([1, 3, 5, 7, 9])

Many set methods can also be written using operators. If acids and bases are two sets, for example, then acids | bases creates a new set containing their union (that is, all the elements from both acids and bases), while acids <= bases tests whether all the values in acids are also in bases. All the operators that sets support are listed in Figure 9.3, on the following page.