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

Python Methods and Functions

This article demonstrates various operations on

# Program for performing various operations on sets
# as we do in mathematics

 
# sets are defined

A = { 0 , 2 , 4 , 6 , 8 }; 

B = { 1 , 2 , 3 , 4 , 5 }; 

 
# union

print ( "Union:" , A | B)

 
# intersection

print ( "Intersection:" , A & amp; B)

  
# difference

print ( "Difference:" , A - B)

 
# symmetric difference

print ( "Symmetric differ ence: " , A ^ B)

Exit:

 ('Union:', set ([0, 1, 2, 3, 4, 5, 6, 8]) ) ('Intersection:', set ([2, 4])) ('Difference:', set ([8, 0, 6])) ('Symmetric difference:', set ([0, 1, 3, 5 , 6, 8])) 




Tutorials