Python Sets: Join Sets

Joining Sets in Python

In Python, you can combine multiple sets using various methods and operators. Each method offers different ways to join sets, depending on whether you want to include duplicates or not. Let’s explore these methods:

Union

The union() method creates a new set containing all unique elements from the provided sets. This method does not modify the original sets but returns a new one.

Example: Join two sets using union():

set1 = {"1984", "Brave New World", "Fahrenheit 451"}
set2 = {7, 14, 21}

set3 = set1.union(set2)
print(set3)  # Output: {'Brave New World', '1984', 'Fahrenheit 451', 7, 14, 21}

You can achieve the same result using the | operator:

set1 = {"1984", "Brave New World", "Fahrenheit 451"}
set2 = {7, 14, 21}

set3 = set1 | set2
print(set3)  # Output: {'Brave New World', '1984', 'Fahrenheit 451', 7, 14, 21}

Joining Multiple Sets

To join more than two sets, you can use the union() method or the | operator. Both approaches allow you to combine multiple sets into one.

Example: Join multiple sets with union():

set1 = {"1984", "Brave New World", "Fahrenheit 451"}
set2 = {7, 14, 21}
set3 = {"Moby Dick", "Pride and Prejudice"}
set4 = {"The Great Gatsby", "The Catcher in the Rye", "To Kill a Mockingbird"}

result = set1.union(set2, set3, set4)
print(result)  # Output: {'1984', 'The Great Gatsby', 'Brave New World', 'Moby Dick', 7, 14, 'Pride and Prejudice', 21, 'Fahrenheit 451', 'To Kill a Mockingbird', 'The Catcher in the Rye'}

Example: Use the | operator to join multiple sets:

set1 = {"1984", "Brave New World", "Fahrenheit 451"}
set2 = {7, 14, 21}
set3 = {"Moby Dick", "Pride and Prejudice"}
set4 = {"The Great Gatsby", "The Catcher in the Rye", "To Kill a Mockingbird"}

result = set1 | set2 | set3 | set4
print(result)  # Output: {'1984', 'The Great Gatsby', 'Brave New World', 'Moby Dick', 7, 14, 'Pride and Prejudice', 21, 'Fahrenheit 451', 'To Kill a Mockingbird', 'The Catcher in the Rye'}

Joining Sets with Other Data Types

The union() method also allows combining sets with other iterable data types such as tuples or lists, resulting in a new set.

Example: Combine a set with a tuple:

set1 = {"1984", "Brave New World", "Fahrenheit 451"}
tuple1 = (7, 14, 21)

result = set1.union(tuple1)
print(result)  # Output: {'Brave New World', '1984', 'Fahrenheit 451', 7, 14, 21}

Note: The | operator is limited to combining only sets and cannot be used with other data types.

Update Method

The update() method adds items from one set into another, modifying the original set directly. It does not return a new set but updates the existing one.

Example: Add items from one set to another using update():

set1 = {"1984", "Brave New World", "Fahrenheit 451"}
set2 = {7, 14, 21}

set1.update(set2)
print(set1)  # Output: {'Brave New World', '1984', 'Fahrenheit 451', 7, 14, 21}

Leave a Comment

Best voice controlled devices. A link to set a new password will be sent to your email address.