Introduction
Difference and symmetric difference help you find what is unique between two groups of items.
Jump into concepts and practice - no test required
Difference and symmetric difference help you find what is unique between two groups of items.
set1.difference(set2) set1 - set2 set1.symmetric_difference(set2) set1 ^ set2
Difference shows items in set1 but not in set2.
Symmetric difference shows items in either set1 or set2 but not both.
a but not in b.a = {1, 2, 3}
b = {2, 3, 4}
print(a.difference(b))- operator.a = {1, 2, 3}
b = {2, 3, 4}
print(a - b)a or b but not both.a = {1, 2, 3}
b = {2, 3, 4}
print(a.symmetric_difference(b))^ operator.a = {1, 2, 3}
b = {2, 3, 4}
print(a ^ b)This program shows how to find difference and symmetric difference between two sets.
set1 = {10, 20, 30, 40}
set2 = {30, 40, 50, 60}
# Difference: items in set1 not in set2
diff = set1 - set2
print("Difference (set1 - set2):", diff)
# Symmetric difference: items in set1 or set2 but not both
sym_diff = set1 ^ set2
print("Symmetric difference:", sym_diff)Difference is not symmetric: a - b is not the same as b - a.
Symmetric difference combines unique items from both sets.
Difference finds items only in the first set.
Symmetric difference finds items in either set but not both.
Use - for difference and ^ for symmetric difference.
A - B return when applied to two sets A and B?A - B means all elements that are in A but not in B.A but not in B matches this definition exactly, others describe different set operations.A and B in Python?^ operator.- is difference, | is union, & is intersection, so only ^ is correct for symmetric difference. A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A - B) A are {1, 2, 3, 4}, in B are {3, 4, 5, 6}. Difference A - B is elements in A not in B, which are {1, 2}.A and B. What is the error? A = {1, 2, 3}
B = {2, 3, 4}
print(A -^ B) -^ which is not a valid Python operator.^ alone, not combined with -. So this causes a syntax error.A = {1, 2, 3, 4, 5} and B = {4, 5, 6, 7}, which expression returns a set of elements that are in either A or B but not in both, and also excludes the element 7 if present?A ^ B gives elements in either set but not both. To exclude 7, subtract {7}.7. (A - B) | (B - A) | {7} incorrectly adds {7}. (A | B) - {7} is union minus 7, which includes common elements. (A & B) - {7} is intersection minus 7, which is wrong.