A Beginner’s Guide to Operations on Sets in Python


Sets are an unordered collection of unique items in Python. You can create a set by using the set() function or by using curly braces {}. For example, {1, 2, 3} is a set containing the integers 1, 2, and 3.

Sets are useful for storing data when you need to ensure that there are no duplicates. They are also helpful for performing mathematical operations such as union, intersection, and difference.

In this blog post, we’ll take a look at how to perform some of the most common operations on sets in Python.

Creating a Set

As we mentioned before, you can create a set by using the set() function or by using curly braces {}. For example, the following two lines of code create the same set:

#python s = set([1, 2, 3]) s = {1, 2, 3}
Code language: Python (python)

If you try to create a set with duplicate elements, only the unique elements will be added to the set. For example, the following code creates a set containing the integers 1, 2, and 3:

#python s = {1, 2, 3, 3} print(s) # Output: {1, 2 ,3}
Code language: Python (python)

As you can see from the output, only the unique elements (1, 2, and 3) are added to the set.

Union of Two Sets in Python

The union of two sets is a new set that contains all the elements from both sets.

union

You can calculate the union of two sets by using the | operator or by using the .union() method.

For example:

#<span style="background-color: inherit; font-family: inherit; font-size: inherit; white-space: pre-wrap; color: initial;">python</span> <span style="background-color: inherit; font-family: inherit; font-size: inherit; white-space: pre-wrap; color: initial;">s = {1, 2, 3}</span> <span style="background-color: inherit; font-family: inherit; font-size: inherit; white-space: pre-wrap; color: initial;">t = {3, 4, 5}</span> <span style="background-color: inherit; font-family: inherit; font-size: inherit; white-space: pre-wrap; color: initial;">u = s | t</span> <span style="background-color: inherit; font-family: inherit; font-size: inherit; white-space: pre-wrap; color: initial;">print(u) # Output: {1, 2, 3, 4, 5}</span>
Code language: HTML, XML (xml)

As you can see from the output above, | operator returns a new set that contains all the elements from both sets (s and t).

The .union() method also returns a new set that contains all elements from both sets (s and t).

However, .union() is preferable over | because it allows you to pass multiple sets as arguments.

For example: u = s.union(t)

The code above calculates the union of two sets (s and t) and stores it in another set u.

In general, .union(*other_sets) calculates the union of more than two sets (in our case other_sets contains only one set but you can pass multiple sets as arguments).

x = {"1", "2", "3"} y = {"10", "20", "50"} z = {"a", "b", "c"} result = x.union(y, z) print(result) #Output: {'2', 'a', '50', '20', '1', '3', 'c', '10', 'b'}
Code language: Python (python)
# Union {0, 1, 2, 3, 4, 5}.union({3, 4, 5, 6}) #Output: {0, 1, 2, 3, 4, 5, 6} {0, 1, 2, 3, 4, 5} | {3, 4, 5, 6} #Output {0, 1, 2, 3, 4, 5, 6}
Code language: PHP (php)

The intersection of Two Sets in Python

If two sets have at least one element in common then we say that these two sets intersect each other. The intersection of two sets is calculated by using & operator or by using .intersection() method.

intersection

.intersection(*other_sets) calculates intersections of more than two sets but & the operator can be used to calculate the intersection of only two sets.

set.intersection(set1, set2 ... etc)
Code language: JavaScript (javascript)
# Intersection {1, 2, 3, 4, 5}.intersection({3, 4, 5, 6}) #Output: {3, 4, 5} {1, 2, 3, 4, 5} & {3, 4, 5, 6} #Output: {3, 4, 5}
Code language: PHP (php)

Example: Compare three sets and return a set with all the same items:

x = {"1", "2", "3", "5"} y = {"12", "5", "16","2"} z = {"2", "7", "5"} result = x.intersection(y, z) print(result) #output: {'5', '2'}
Code language: PHP (php)

The python set difference function

The – operator can be used to take the difference between two sets. The function .difference() returns a set that is the difference between two sets.

Difference
set.difference(set)
Code language: JavaScript (javascript)
# Difference {1, 2, 3, 4}.difference({2, 3, 5}) #Output: {1, 4} {1, 2, 3, 4} - {2, 3, 5} #Output: {1, 4}
Code language: PHP (php)

Now, let’s look at an example to see how the set difference works in Python. Let’s say we have two sets, A and B, that overlap and we want to find the difference between them.

A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # Python set differene method result = setA.difference(setB) # printing print(result) # Output: {1, 2, 3}
Code language: PHP (php)

Python Symmetric Difference

The symmetric difference between two sets is a set of elements that are in either set, but not in their intersection.

The symmetric difference of two sets A and B is the set of elements which are in either of the sets A or B but not in both.

Symmetric difference with
set.symmetric_difference(set)
Code language: JavaScript (javascript)

Return a set containing items from both sets, except duplicates.

Example 1:

{1, 2, 3, 4}.symmetric_difference({2, 3, 5}) #Output: {1, 4, 5} {1, 2, 3, 4} ^ {2, 3, 5} #Output: {1, 4, 5}
Code language: PHP (php)

Example 2:

SetA = {'a', 'b', 'c', 'd', 'e'} SetB = {'c', 'd', 'e','f' } # returns all items to result variable except the items on intersection result = SetA.symmetric_difference(SetB) print(result) # Output: {'a', 'f', 'b'}
Code language: PHP (php)

Superset check

The Python issuperset() method to check if a set is a superset of another.

set_a.issuperset(set_b)
Code language: CSS (css)

Example 1:

{1, 2}.issuperset({1, 2, 3}) # False<br>{1, 2} >= {1, 2, 3} # False
Code language: Python (python)

Example 2:

SetA_super = {1, 2, 3, 4, 5, 6, 7} SetB = {1, 2, 3, 4} result = SetA_super.issuperset(SetB) print(result) #Output: True
Code language: Python (python)

Since all SetB elements are in SetA_super, SetA_super is a superset of SetB.

Check whether a Set Is a Subset in Python

To check if a set A is a subset of set B in Python, use the issubset() method.

# Subset check {1, 2}.issubset({1, 2, 3}) # True {1, 2} <= {1, 2, 3} # True
Code language: Python (python)

For example:

SetA = {1, 2, 3, 4} SetB = {1, 2, 3, 4, 5, 6} print(SetA.issubset(SetB)) #Output: True print(SetA <= SetB) #Output: True
Code language: Python (python)

Python Set isdisjoint() method with examples

The isdisjoint() method of the Python Set class checks to see if the two sets are disjoint sets. If the sets are not the same, this method returns true. If they are the same, it returns false. If there is nothing in both sets that is the same, then the two sets are not connected.

set.isdisjoint(iterable)
Code language: JavaScript (javascript)

Set A {1, 2, 3} and Set B {4, 5, 6} are not the same set because they don’t have any items in common.

# Disjoint check {1, 2}.isdisjoint({3, 4}) # True {1, 2}.isdisjoint({1, 4}) # False
Code language: Python (python)

Python sets are unique collections of items, and can be created from any iterable. Sets are mutable, which means they can be modified after they’re created.

Sets are unordered, which means that the items in a set are not sorted in any particular order. This can be useful when you want to create a collection of items that doesn’t have any particular order.

Sets cannot contain duplicate items, so if you try to add an item to a set that already exists in the set, it will not be added again. This can be useful for avoiding duplicate data.

Python also provides a built-in set type, which is similar to the sets described above but has some additional features. The built-in set type supports operations like union, intersection, and difference, as well as some other handy features. Check out the documentation for more information on what you can do with sets in Python.

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts