Set Operations

Python provides a variety of operations that can be performed on sets. These operations include the basic mathematical operations we perform on sets in mathematics and additionally, some more operations that help us manipulate and compare sets.

Basic Set Operations

Let’s start with the fundamental set operations:

Union

Union of A and B is a set of all elements from both sets. Union is performed using | operator. Same can be accomplished using the union() method. Here’s an example:

1A = {1, 2, 3, 4, 5}
2B = {4, 5, 6, 7, 8}
3
4print(A | B)
5print(A.union(B))
6print(B.union(A))

Intersection

Intersection of A and B is a set of elements that are common in both the sets. The intersection is performed using & operator. You can also use the intersection() method.

1A = {1, 2, 3, 4, 5}
2B = {4, 5, 6, 7, 8}
3
4print(A & B)
5print(A.intersection(B))
6print(B.intersection(A))

Difference

Difference of the set B from set A (A - B) is a set of elements that are only in A but not in B. Similarly, B - A is a set of elements in B but not in A. Difference is performed using - operator. The same can be accomplished using the difference() method.

1A = {1, 2, 3, 4, 5}
2B = {4, 5, 6, 7, 8}
3
4print(A - B)
5print(A.difference(B))
6print(B - A)
7print(B.difference(A))

Checking if a Set is a Subset of Another

A set A is said to be the subset of set B if all elements of A are in B. We can check this by A <= B or A.issubset(B).

1A = {1, 2, 3}
2B = {1, 2, 3, 4, 5}
3
4print(A <= B)
5print(A.issubset(B))

Note

Set operations such as union and intersection treat string objects as individual entities in the set. However, in cases like subset checking, the string objects are iterated over and treated as a sequence of characters.