find set difference in python by R4R Team

- the symmetric difference, also known as the disjunctive union, of two sets is the set of elements which are in either of the sets and not in their intersection.

Example

set1 is {1,2,3}
set2 is {2,3}

then set1-set2={1}
and set2-set1={}

Syntax-

set1.difference(set2)


program-

set1=set([1,2,3])
set2=set([4,5,6])

print(set2-set1)
print(set2.difference(set1))

print(set1.difference(set2))
print(set1-set2)

print(set1-set1)
print(set2-set2)

set1=set([1,2,3,4])
set2=set([4])

print(set1.difference(set2))
print(set2.difference(set1))


output-

{4, 5, 6}
{4, 5, 6}
{1, 2, 3}
{1, 2, 3}
set()
set()
{1, 2, 3}
set()


-In this program, we have two set {1,2,3} and {4,5,6} then we find the set difference by the two ways - first is by function difference() and second method is by '-' operator.
-{1,2,3}-{4,5,6} will give {1,2,3} because 1,2,3 is not present in second set.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!