Join Operations II
Lesson 7 of 11 in Coddy's Sets in Python course.
The difference between two sets includes the elements that are present in the first set but not in the second set. You can perform a difference using the difference() method or the - operator.
set1 = {"apple", "banana", "cherry"}
set2 = {"banana", "date", "fig"}
# Using difference() method
difference_set = set1.difference(set2)
print(difference_set) # Output: {'apple', 'cherry'}
# Using - operator
difference_set = set1 - set2
print(difference_set) # Output: {'apple', 'cherry'}The symmetric difference between two sets includes the elements that are present in either set, but not in both. You can perform a symmetric difference using the symmetric_difference() method or the ^ operator.
set1 = {"apple", "banana", "cherry"}
set2 = {"banana", "date", "fig"}
# Using symmetric_difference() method
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # Output: {'apple', 'cherry', 'date', 'fig'}
# Using ^ operator
symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set) # Output: {'apple', 'cherry', 'date', 'fig'}These join operations allow you to identify unique elements between sets and perform more advanced data comparisons.
Challenge
Easy- Create two sets:
set1with the items"apple","banana", and"cherry", andset2with the items"banana","date", and"elderberry". - Compute the difference of
set1withset2and store the result in a variable nameddifference_result. - Compute the symmetric difference of
set1withset2and store the result in a variable namedsymmetric_difference_result. - Print both
difference_resultandsymmetric_difference_result.
Try it yourself
All lessons in Sets in Python
1Sets
IntroductionSets in PythonAccess ItemsAdd ItemsRemove ItemsJoin Operations IJoin Operations IIAll Methods