Menu
Coddy logo textTech

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.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy
  1. Create two sets: set1 with the items "apple", "banana", and "cherry", and set2 with the items "banana", "date", and "elderberry".
  2. Compute the union of set1 and set2 and store the result in a variable named union_result.
  3. Compute the intersection of set1 and set2 and store the result in a variable named intersection_result.
  4. Print both union_result and intersection_result.

Try it yourself

All lessons in Sets in Python