A set an unordered collection of items. Every element is unique and which are immutable. Set elements are enclosed in curly braces {}.
Create a set
#creating set with elements
set1 = {1,2,3,4}
#creating empty set
set2 = set()
setA = {1,2,3,4,5}
setB = {4,5,6,7,8}
-
Union: It is a set of all elements from both sets. Union is performed using | operator.
setA = {1,2,3,4,5}
setB = {4,5,6,7,8}
print(setA|setB)
{1, 2, 3, 4, 5, 6, 7, 8}
-
Intersection: It is a set of elements that are common in both sets. Intersection is performed using & operator.
setA = {1,2,3,4,5}
setB = {4,5,6,7,8}
print(setA&setB)
{4,5}
-
Difference: It is a set of elements that are only in setA but not in setB. Difference is performed using - operator.
setA = {1,2,3,4,5}
setB = {4,5,6,7,8}
print(setA-setB)
print(setB-setA)
{1,2,3}
{6,7,8}
-
Symmetric Difference: It is a set of elements in both setA and setB except those are common in both. Symmetric difference is performed using ^ operator.
setA = {1,2,3,4,5}
setB = {4,5,6,7,8}
print(setA^setB)
{1, 2, 3, 6, 7, 8}