[파이썬] 집합의 합집합, 교집합, 차집합

In Python, sets are a built-in data type that represent a collection of unique elements. Sets can be manipulated using various operations, including union, intersection, and difference. In this blog post, we will explore how to perform these operations using Python.

Union (합집합)

The union of two sets A and B is a set that contains all the elements from both A and B. In Python, the union operation can be performed using the union() method or the | operator. Here’s an example:

A = {1, 2, 3}
B = {3, 4, 5}

union_set = A.union(B)
# or union_set = A | B

print(union_set)  # Output: {1, 2, 3, 4, 5}

Intersection (교집합)

The intersection of two sets A and B is a set that contains only the elements that are common to both A and B. Python provides the intersection() method or the & operator to perform the intersection operation. Here’s an example:

A = {1, 2, 3}
B = {3, 4, 5}

intersection_set = A.intersection(B)
# or intersection_set = A & B

print(intersection_set)  # Output: {3}

Difference (차집합)

The difference between two sets A and B is a set that contains the elements that are in A but not in B. The difference operation can be performed in Python using the difference() method or the - operator. Here’s an example:

A = {1, 2, 3}
B = {3, 4, 5}

difference_set = A.difference(B)
# or difference_set = A - B

print(difference_set)  # Output: {1, 2}

Conclusion

In this blog post, we explored how to perform union, intersection, and difference operations on sets in Python. Sets are a powerful data type that can be used for various purposes, including removing duplicates from a list, checking for membership, and performing set operations. Understanding these operations is essential for working with sets effectively.