Menu
Coddy logo textTech

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 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 difference of set1 with set2 and store the result in a variable named difference_result.
  3. Compute the symmetric difference of set1 with set2 and store the result in a variable named symmetric_difference_result.
  4. Print both difference_result and symmetric_difference_result.

Try it yourself

All lessons in Sets in Python