Hi everyone, welcome back. In these examples, we will be going over how to combine sets in Python. Sets can be used to store a collection of data. A set in Python does not allow duplicate values. The elements within a set are immutable, though elements can still be added or removed. The elements within a set are unordered and unindexed. With this introduction out of the way, let’s get into it.
union() Function
The union() function can be used to create a new set containing values of two or more given sets. Let’s see an example:
mySet = {1, 2, 3, 4}
mySet2 = {3, 4, 5, 6}
mySet3 = mySet.union(mySet2)
print(mySet3)Output:
{1, 2, 3, 4, 5, 6}
In the example above, we can see that we used the union() function to create a new set. We can verify the new set contains all the values from the given sets by printing it and checking the output.
update() Function
The update() function can be used to add the values of one set to another. Let’s see an example:
mySet = {1, 2, 3, 4}
mySet2 = {3, 4, 5, 6}
mySet.update(mySet2)
print(mySet)Output:
{1, 2, 3, 4, 5, 6}