मराठी
तामिळनाडू बोर्ड ऑफ सेकेंडरी एज्युकेशनएचएससी विज्ञान इयत्ता १२

Explain the different set operations supported by python with suitable examples.

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'}

shaalaa.com
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 9: Lists, Tuples, Sets and Dictionary - Evaluation [पृष्ठ १६९]

APPEARS IN

सामाचीर कलवी Computer Science [English] Class 12 TN Board
पाठ 9 Lists, Tuples, Sets and Dictionary
Evaluation | Q 4. | पृष्ठ १६९
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×