Sets can be used to carry out mathematical set operations following a different operation on set can be performed
- Union (|)
- Intersection (&)
- difference (-)
- symmetric difference (^)
- Two sets can be added together.
- Union is performed using | operator same can be achived using built in function union().
Syntax:
SetA=set()
SetB=set()
#Using | Operator
result=SetA | SetB
#Using Built in Function .union()
result=SetA.union(SetB)
Example:
#Initialize Two Set
A={1,5,2}
B={6,7,8,9}
#using built in method .union()
result=A.union(B)
print(result)
#Result:{1, 2, 5, 6, 7, 8, 9}
#Using | operator
result1=A | B
print(result1)
#Result:{1, 2, 5, 6, 7, 8, 9}
Output:
{1, 2, 5, 6, 7, 8, 9}
{1, 2, 5, 6, 7, 8, 9}
- A new set can also be constructed by determining which members two sets have in common.
- The intersection is performed using & operator same can be achieved using built-in function intersection().
Syntax:
SetA=set()
SetB=set()
#Using & operator
result=SetA & SetB
#using intersection() method
result=SetA.intersection(SetB)
Example:
#Initialize Two Set
A={1,5,2}
B={3,2,1,6,8,7}
#using built in method .intersection()
result=A.intersection(B)
print(result)
#Result:{1, 2}
#Using & operator
result1=A & B
print(result1)
#Result:{1, 2}
Output:
{1, 2}
{1, 2}
- Two sets can also be subtracted.
- The difference can be performed using a - operator or the same thing can be achieved using difference().
- Here A-B Result is a Different result than B-A.
A-B: The elements included in A, but not included in B. B-A: The elements included in B, but not included in A.
Syntax:
SetA=set()
SetB=set()
#using - Operator
result=SetA - SetB
#Using .difference()
result=SetA.difference(SetB)
Example:
A={1,2,3,5,4}
B={2,4,8,6,9}
#using built in method .difference()
result=A.difference(B)
print(result)
#Result:{1, 3, 5}
#Using - operator
result1=A - B
print(result1)
#Result:{1, 3, 5}
Output:
{1, 3, 5}
{1, 3, 5}
- The symmetric_difference() method returns a set that contains all items from both set, but not the items that are present in both sets.
- symmetric Difference can be performed using ^ operator or the same thing can be achieved using symmetric_difference().
Syntax:
SetA=set()
SetB=set()
#Using ^ Operator
result=SetA ^ SetB
#Using symmetric_difference()
result=SetA.symmetric_difference(SetB)
Example:
#Initialize Two Diffrent Sets
A={1,2,3,5,4}
B={2,1,8,6,9}
#using built in method .symmetric_difference()
result=A.symmetric_difference(B)
print(result)
#Result:{3, 4, 5, 6, 8, 9}
#Using ^ operator
result1=A ^ B
print(result1)
#Result:{3, 4, 5, 6, 8, 9}
Output:
{3, 4, 5, 6, 8, 9}
{3, 4, 5, 6, 8, 9}