[파이썬] 집합의 요소 대칭 차집합 연산

In Python, sets are a useful data structure for storing unordered collections of unique elements. One common operation performed on sets is the symmetric difference, also known as the “exclusive OR” (XOR) operation. The symmetric difference of two sets is the set of elements that are present in one set or the other, but not in both.

Let’s say we have two sets, set A and set B, and we want to find the symmetric difference between them. Here’s how we can perform this operation in Python:

# Define two sets
set_A = {1, 2, 3, 4, 5}
set_B = {4, 5, 6, 7, 8}

# Find the symmetric difference
symmetric_difference = set_A ^ set_B

print(symmetric_difference)

Output:

{1, 2, 3, 6, 7, 8}

In the above example, we first define two sets, set_A and set_B, each containing a few elements. We then use the XOR operator (^) to perform the symmetric difference operation between the two sets. Finally, we print the result, which is a new set that contains all the elements present in set_A and set_B, except for the common elements.

It’s important to note that the symmetric difference operation does not modify the original sets. Instead, it returns a new set as the result.

The ^ operator is the shorthand notation for performing the symmetric difference operation in Python. Alternatively, you can also use the symmetric_difference() method to achieve the same result:

symmetric_difference = set_A.symmetric_difference(set_B)

Both approaches yield the same output.

In conclusion, the symmetric difference operation allows us to find the elements that are unique to each set and not common between them. This can be useful in various scenarios, such as comparing two sets of data or identifying differences between sets. Python’s built-in set operations and operators make it easy to perform such operations efficiently.