How to Add Sets in Python?

Python Tutorials

Addition of two or more sets combines the items of different sets into a single set object. For example, the addition of {1, 2, 5} and {2, 6, 3} results in {1, 2, 5, 6, 3}.

In Python, you can add (combine) sets in the following ways.

Use set.union() to Add Sets

Call the set.union(set1, set2, ..., setn) method with the set objects that need to be combined into a single set.

>>> set1 = {1, 2, 5}
>>> set2 = {2, 6, 3}
>>> result = set.union(set1, set2)
{1, 2, 3, 5, 6}

To combine more than two sets, pass the set objects as parameters to this method.

>>> result = set.union({1, 2}, {5, 7}, {8, 0})
{0, 1, 2, 5, 7, 8}

Use | operator to Add Sets

Specify the sets separated by the | operator to add them to a single set object.

>>> set1 = {1, 2, 5}
>>> set2 = {2, 6, 3}
>>> set3 = {9, 1}
>>> result = set1 | set2 | set3
{1, 2, 3, 5, 6, 9}

Use set.update() to Add Sets

Call the set1.update(set2) method with the second set object as set2 to add items of set2 to set1.

>>> set1 = {'a', 'b', 'c'}
>>> set2 = {'d', 'e', 'f'}
>>> set1.update(set2)
>>> set1
{'f', 'd', 'e', 'b', 'c', 'a'}

Leave a Reply

Your email address will not be published. Required fields are marked *