← Back to Chapters

Python Join Sets

? Python Join Sets

⚡ Quick Overview

In Python, you can join (combine) sets to create a new set that contains all unique elements from the given sets. The most common ways to join sets are:

  • union() method
  • | (pipe) operator
  • update() method to modify an existing set in place

? Key Concepts

  • Sets automatically remove duplicate elements.
  • union() returns a new set and does not change the original sets.
  • | operator is a shorthand way of doing union.
  • update() adds all elements from another set (or iterable) into the original set.
  • You can join sets with any iterable (lists, tuples, sets, etc.).

? Syntax and Theory

  • Union using method:
    result = set1.union(set2)
  • Union using operator:
    result = set1 | set2
  • Update in place:
    set1.update(set2)

? Code Examples

? Union of two sets using union() and |
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Using union()
joined_set = set1.union(set2)
print(joined_set)  # {1, 2, 3, 4, 5}

# Using |
joined_set2 = set1 | set2
print(joined_set2)  # {1, 2, 3, 4, 5}
? Update one set with elements from another
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Update set1 with all elements of set2
set1.update(set2)
print(set1)  # {1, 2, 3, 4, 5}

? Output and Explanation

? What happens when you join sets?

In the first example, set1.union(set2) and set1 | set2 both create a new set containing all unique elements from set1 and set2.

The output will look like:

{1, 2, 3, 4, 5}

In the second example, set1.update(set2) modifies set1 directly. After the update, set1 becomes:

{1, 2, 3, 4, 5}

Notice how the duplicate element 3 appears only once in the final set, because sets automatically remove duplicates.

? Tips and Best Practices

  • Use union() when you need a new combined set without changing the originals.
  • Use update() when you want to add elements directly into an existing set.
  • Remember that sets do not preserve order and do not allow duplicates.
  • You can pass any iterable (like a list or tuple) to update(), not just another set.

? Try It Yourself

  • Create two sets of numbers and join them using union(). Print the result.
  • Repeat the same using the | operator and compare the output.
  • Create a set and then call update() with a list of new values. Check how the set changes.
  • Experiment with sets that have overlapping elements and observe how duplicates are handled.