Open In App

Python Set Operations (Union, Intersection, Difference and Symmetric Difference)

Last Updated : 22 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Sets are a fundamental data structure in Python that store unique elements. Python provides built-in operations for performing set operations such as union, intersection, difference and symmetric difference. In this article, we understand these operations one by one.

Union of sets

The union of two sets combines all unique elements from both sets.

Syntax:

set1 | set2 # Using the ‘|’ operator

set1.union(set2) # Using the union() method

Example:

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

# Using '|' operator
res1 = A | B
print("using '|':", res1)

# Using union() method
res2 = A.union(B)
print("using union():",res2)

Output
using '|': {1, 2, 3, 4, 5, 6}
using union(): {1, 2, 3, 4, 5, 6}

Explanation: | operator and union() method both return a new set containing all unique elements from both sets .

Intersection of sets

The intersection of two sets includes only the common elements present in both sets.

Syntax:

set1 & set2 # Using the ‘&’ operator

set1.intersection(set2) # Using the intersection() method

Example:

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

# Using '&' operator
res1 = A & B
print("using '&':",res1)

# Using intersection() method
res2 = A.intersection(B)
print("using intersection():",res2)

Output
using '&': {3, 4}
using intersection(): {3, 4}

Explanation: & operator and intersection() method return a new set containing only elements that appear in both sets.

Difference of sets

The difference between two sets includes elements present in the first set but not in the second.

Syntax:

set1 – set2 # Using the ‘-‘ operator

set1.difference(set2) # Using the difference() method

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

# Using '-' operator
res1 = A - B
print("using '-':", res1)

# Using difference() method
res2 = A.difference(B)
print("using difference():", res2)

Output
using '-': {1, 2}
using difference(): {1, 2}

Explanation: - operator and difference() method return a new set containing elements of A that are not in B.

Symmetric Difference of sets

The symmetric difference of two sets includes elements that are in either set but not in both.

Syntax:

set1 ^ set2 # Using the ‘^’ operator

set1.symmetric_difference(set2) # Using the symmetric_difference() method

Example:

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

# Using '^' operator
res1 = A ^ B
print("using '^':", res1)

# Using symmetric_difference() method
res2 = A.symmetric_difference(B)
print("using symmetric_difference():", res2)

Output
using '^': {1, 2, 5, 6}
using symmetric_difference(): {1, 2, 5, 6}

Explanation: ^ operator and symmetric_difference() method return a new set containing elements that are in either A or B but not in both.



Next Article
Practice Tags :

Similar Reads

  翻译: