Join Sets

 

What You'll Learn: In this tutorial, you'll discover different ways to join two or more sets in Python. Sets are useful for storing unique items, and you can combine them in various ways.

Methods to Join Sets

  1. Union:
    • Combines all items from both sets.
    • Example Code:

      python
      set1 = {"a", "b", "c"}
      set2 = {1, 2, 3}
      set3 = set1.union(set2)
      print(set3)
      
    • Output: {'a', 1, 2, 3, 'b', 'c'}
       
  2. Update:
    • Inserts all items from one set into another, modifying the original set.
    • Example Code:

      python
      set1 = {"a", "b", "c"}
      set2 = {1, 2, 3}
      set1.update(set2)
      print(set1)
      
    • Output: {'a', 1, 2, 3, 'b', 'c'}
       
  3. Intersection:
    • Keeps only the items present in both sets.
    • Example Code:

      python
      set1 = {"apple", "banana", "cherry"}
      set2 = {"google", "apple", "microsoft"}
      set3 = set1.intersection(set2)
      print(set3)
      
    • Output: {'apple'}
       
  4. Difference:
    • Keeps the items from the first set that are not in the other set.
    • Example Code:

      python
      set1 = {"apple", "banana", "cherry"}
      set2 = {"google", "microsoft", "apple"}
      set3 = set1.difference(set2)
      print(set3)
      
    • Output: {'banana', 'cherry'}
       
  5. Symmetric Difference:
    • Keeps all items except the duplicates from both sets.
    • Example Code:

      python
      set1 = {"apple", "banana", "cherry"}
      set2 = {"google", "microsoft", "apple"}
      set3 = set1.symmetric_difference(set2)
      print(set3)
      
    • Output: {'banana', 'google', 'cherry', 'microsoft'}
       

Try It Yourself: Fun Exercises

  1. Combine Your Favorite Snacks:
    • Create two sets of different snacks.
    • Use the union() method to combine them into one set.
  2. Find Common Hobbies:
    • Write two sets of hobbies you and your friend like.
    • Use the intersection() method to find hobbies you both enjoy.
  3. Unique Sports:
    • Create sets of sports you like and sports your friend likes.
    • Use the symmetric_difference() method to find sports only one of you likes.

Summary:

In this Python tutorial, we learned various methods to join sets, including union(), update(), intersection(), difference(), and symmetric_difference(). These methods allow you to combine, update, and find unique items in sets effectively. Keep experimenting and have fun with sets in Python!