Python Joining Sets

Python – Join Sets

In Python, sets are unordered collections of unique elements. They are widely used in various programming scenarios to store and manipulate data. One common operation performed on sets is to join or merge them together. This can be achieved using several methods and operators provided by Python.

1. Using the union() method

The union() method is used to combine two or more sets into a new set. It returns a new set that contains all the elements from the original sets, excluding any duplicates.

Here’s an example:


# Define two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Join the sets using union()
joined_set = set1.union(set2)

# Print the joined set
print(joined_set)

The output of the above code will be:


{1, 2, 3, 4, 5}

As you can see, the joined set contains all the unique elements from both set1 and set2.

2. Using the update() method

The update() method is used to add elements from one set to another set. It modifies the original set by adding the elements from the specified set(s).

Here’s an example:


# Define two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Join the sets using update()
set1.update(set2)

# Print the updated set
print(set1)

The output of the above code will be:


{1, 2, 3, 4, 5}

As you can see, the update() method adds all the elements from set2 to set1, resulting in a joined set.

3. Using the | (pipe) operator

In Python, the | (pipe) operator can also be used to join two or more sets. It returns a new set that contains all the elements from the original sets, excluding any duplicates.

Here’s an example:


# Define two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Join the sets using the | operator
joined_set = set1 | set2

# Print the joined set
print(joined_set)

The output of the above code will be:


{1, 2, 3, 4, 5}

As you can see, the joined set contains all the unique elements from both set1 and set2.

Conclusion

Joining sets in Python is a common operation that can be done using various methods and operators. The union() method, update() method, and the | (pipe) operator are all effective ways to combine sets and create a new set without any duplicates. Depending on the specific requirements of your program, you can choose the method that best suits your needs.

Scroll to Top