Python set operations | Basics with example code

Python Sets have mathematical set operations like union, intersection, difference, and symmetric difference. You can do this operation using the operators or inbuilt methods.

See below Operator for set operations:

  • | for union
  • & for intersection
  • – for difference
  • ^ for symmetric difference
Python set operations

Python set operations exmaples

Simple example code.

Set Union, S1|S2 operation

Union is performed using | operator or using the union() method.

fib = {1, 1, 2, 3, 5, 8}
prime = {2, 3, 5, 7, 11}

print(fib | prime)

# or using method
res = fib.union(prime)
print(res)

Output: {1, 2, 3, 5, 7, 8, 11}

Set Intersection, S1&S2 operation

The intersection is performed using & operator using the intersection() method.

fib = {1, 1, 2, 3, 5, 8}
prime = {2, 3, 5, 7, 11}

print(fib & prime)

# or using method
res = fib.intersection(prime)
print(res)

Output: {2, 3, 5}

Set Difference, S1-S2 operation

The difference is performed using – operator or using the difference() method.

fib = {1, 1, 2, 3, 5, 8}
prime = {2, 3, 5, 7, 11}

print(fib - prime)

# or using method
res = fib.difference(prime)
print(res)

Output: {8, 1}

Set Symmetric Difference, S2^S2 operation

The symmetric difference is performed using the ^ operator or using the symmetric_difference() method.

fib = {1, 1, 2, 3, 5, 8}
prime = {2, 3, 5, 7, 11}

print(fib ^ prime)

# or using method
res = fib.symmetric_difference(prime)
print(res)

Output: {1, 7, 8, 11}

Easy to understand

OperationNotationMeaning
IntersectionA ∩ Ball elements which are in both and
UnionA ∪ Ball elements which are in either or (or both)
DifferenceA − Ball elements which are in but not in
Complement(or)all elements which are not in

Sets and frozen sets support the following operators –

key in s         # containment check
key not in s   # non-containment check
s1 == s2       # s1 is equivalent to s2
s1 != s2       # s1 is not equivalent to s2
s1 <= s2    # s1is subset of s2 s1 < s2     # s1 is proper subset of s2 s1 >= s2             # s1is superset of s2
s1 > s2     # s1 is proper superset of s2
s1 | s2        # the union of s1 and s2
s1 & s2        # the intersection of s1 and s2
s1 – s2        # the set of elements in s1 but not s2
s1 ˆ s2        # the set of elements in precisely one of s1 or s2

Do comment if you have any doubts and suggestions on this Python set basic tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.