Advertisements
Advertisements
प्रश्न
Explain the different set operations supported by python with suitable examples.
Advertisements
उत्तर
Set Operations:
As you learned in mathematics, python has also supported the set operations such as Union, Intersection, difference and Symmetric difference.
(i) Union: It includes all elements from two or more sets.

In python, the operator | is used to the union of two sets. The function union( ) is also used to join two sets in python.
Example: Program to Join (Union) two sets using union operator
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
U_set=set_A|set_B
print(U_set)
Output: {2, 4, 6, 8, 'A', 'D', 'C', 'B'}
(ii) Intersection: It includes the common elements in two sets.

The operator & is used to intersect two sets in python. The function intersection( ) is also used to intersect two sets in python.
Example: Program to insect two sets using intersection operator.
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B)
Output: {'A', 'D'}
Example: Program to insect two sets using intersection function
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.intersection(set_B))
Output: {'A', 'D'}
(iii) Difference: It includes all elements that are in the first set (say set A) but not in the second set (say set B).

The minus (-) operator is used to difference set operation in python. The function difference( ) is also used to difference operation.
Example: Program to the difference of two sets using minus operator
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B)
Output: {2, 4}
Example: Program to the difference of two sets using difference function
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.diff erence(set_B))
Output: {2, 4}
(iv) Symmetric difference: It includes all the elements that are in two sets (say sets A and B) but not the one that is common to two sets.

The caret (^) operator is used for the symmetric difference set operation in python. The function symmetric_difference( ) is also used to do the same operation.
Example: Program to the symmetric difference of two sets using caret operator.
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B)
Output: {2, 4, 'B', 'C'}
Example: Program to the difference of two sets using symmetric difference function
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.symmetric_difference(set_B))
Output: {2, 4, 'B', 'C'}
