Join Operations I
Lesson 6 of 11 in Coddy's Sets in Python course.
The union of two sets includes all unique elements from both sets. You can perform a union using the union() method or the | operator.
set1 = {"apple", "banana", "cherry"}
set2 = {"banana", "date", "fig"}
# Using union() method
union_set = set1.union(set2)
print(union_set) # Output: {'apple', 'banana', 'cherry', 'date', 'fig'}
# Using | operator
union_set = set1 | set2
print(union_set) # Output: {'apple', 'banana', 'cherry', 'date', 'fig'}The intersection of two sets includes only the elements that are present in both sets. You can perform an intersection using the intersection() method or the & operator.
set1 = {"apple", "banana", "cherry"}
set2 = {"banana", "date", "fig"}
# Using intersection() method
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {'banana'}
# Using & operator
intersection_set = set1 & set2
print(intersection_set) # Output: {'banana'}These basic join operations allow you to combine sets in powerful ways, enabling efficient data manipulation and comparison.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
Easy- Create two sets:
set1with the items"apple","banana", and"cherry", andset2with the items"banana","date", and"elderberry". - Compute the union of
set1andset2and store the result in a variable namedunion_result. - Compute the intersection of
set1andset2and store the result in a variable namedintersection_result. - Print both
union_resultandintersection_result.
Try it yourself
All lessons in Sets in Python
1Sets
IntroductionSets in PythonAccess ItemsAdd ItemsRemove ItemsJoin Operations IJoin Operations IIAll Methods