+ 1
Can some one explain me difference operator in sets
with the help of a python code explanation
5 Answers
+ 2
Set difference operation is not commutative, which means a-b and b-a are different. If you try this, a-b will give you set([1, 2, 3]) as I wrote above, but b-a will give you set([7, 8, 9]).
Using the same condition for b-a, 4 to 9 can be in b-a, but 1 to 6 should not be in b-a. So the result becomes 7 to 9.
If you want elements which in a or b but not both in a and b, you can use symmetric difference set operator ^. a^b will give you set([1, 2, 3, 7, 8, 9]).(Same with (a-b)|(b-a) or (a|b)-(a&b))
+ 2
In set theory, 'set difference' is defined by "set of elements 1) contained in A and 2) not contained in B" ({x|xâA,xâB}), where A and B are sets.
Let's watch this code:
a = set([1,2,3,4,5,6])
b = set([4,5,6,7,8,9])
print (a-b)
There is a set with element from 1 to 6, and another set with element from 4 to 9. The first condition(elements in set A) informs us that 1 to 6 can be in a-b, and the second condition(elements not in set B) informs us that 4 to 9 should not be in a-b. Since both condition should be satisfied, 4 to 6, which are in both A and B, can't be in a-b. So only 1 to 3 should be in a-b, and the result will be 'set([1,2,3])'.
I think it is the best way for you to change the numbers and check the results, change&check, and change&check again. It will be the best way to understand how does it work.
-I'm sorry if it is difficult to understand..
+ 2
oookk but if 4,5,6 are removed then why it didnt print 7,8,9 too
+ 1
tnx bro
0
or sis