Back to articles list Articles
7 minutes read

Python Set Operations: Union, Intersection, and Difference – With 10 Examples

Are you stuck trying to use Python set operations? Want to know how to use them? This introduction gives you a basic understanding of set operations in Python.

In this tutorial, we look at set operations in Python and other operations performed on sets. Furthermore, we look at the different methods on sets as well as examples of set operations in Python. Check out this article for a deeper look into combinatorics with Python.

A set is a collection of unordered elements. Each element must be distinct and immutable. However, a set itself is mutable.

You may add or remove items from sets. You may also perform mathematical operations on them, such as union, intersection, and difference.

The concept of a set has been explicitly translated from mathematics into programming languages like Python. With it, some extremely helpful methods have come, such as union(), intersection(), and difference(), also directly translated from mathematics.

Sets are not simply a fundamental concept in mathematics. Throughout your programming career, you'll likely come across a variety of challenges that may be solved significantly more quickly by using sets.

If you are a complete beginner to Python, we recommend you check out this track. If you are a beginner with some knowledge of Python, check out the course Python Basics Part 3, which covers the basics of variables, lists, conditional statements, loops, and functions.

Sets and Set Operations in Python

A set is defined by enclosing all of the items (i.e., elements) in curly brackets and separating them with a comma or using the built-in set() method. It can include an unlimited number of elements of various categories (integer, float, tuple, string, etc.).

However, a set may not contain mutable items such as lists, sets, or dictionaries. Visit this article to learn more about the differences between lists, tuples, and sets. LearnPython.com is an incredible platform that helps you get started with Python.

Empty sets can be slightly tricky to use in Python. In Python, empty curly braces result in an empty dictionary; however, we cannot use them to initialize an empty set. Instead, we use the set() function without any arguments to create a set with no elements.

See the code below to understand these concepts:

# A set of integers
int_set = {10, 20, 30, 40, 50}

# A set of mixed data types
mixed_set = {9, "This is a set element", (1, 2)}

# All set elements are unique
my_set = {1, 2, 3, 1, 3, 3}
print(my_set) # Output: {1, 2, 3}

# A set can be made from a list
my_set = set([1, 2, 3, 2, 4, 5, 5])
print(my_set) # Output: {1, 2, 3, 4, 5}

Modifying a Set in Python

Indexing and slicing cannot be used to access or update an element of a set. The set data type does not support it since sets are not ordered.

The add() method is used to add a single element, and the update() method is used to update multiple components. Tuples, lists, strings, and other sets may be passed to the update() method. Duplicates are avoided in all circumstances.

The following code illustrates these examples.

# Initialize a set
my_set = {11, 60}

# Add an element to the set
# Output: {11, 21, 60}
my_set.add(21)
print(my_set)

# Add more than one element to the set
# Output: {8, 11, 13, 20, 21, 60}
my_set.update([20, 13, 8])
print(my_set)

Removing Elements From a Set

The methods discard() and remove() are used to delete a specific item from a set. They are identical with only one difference. The discard() method leaves the set unmodified If the element is not present in the set. The remove() method, on the other hand, throws an error if the element is not present in the set.

The use of these functions is demonstrated in the example below.

# Initialize a set
my_set = {10, 20, 30, 40, 50}
print(my_set)

# Discard an element
my_set.discard(40)
print(my_set) # Output: {10, 20, 30, 50}

# Remove an element
my_set.remove(60) # KeyError!

We may also use the pop() method to remove and return an item. However, there is no way to know which item will be popped because the set is an unordered data type. It's absolutely random!

Note that the clear() method is used to delete all elements from a set.

# Initialize a set
my_set = set("LearnPython")

# Pop an element
print(my_set.pop()) # Output: random element

# Clear the set
my_set.clear()
print(my_set) # Output: set()

In Python, most, but not all, set operations are performed in one of two ways: by an operator or by a method. Before we look at how different set operations work in Python, it's important to understand the distinction between an operator and a method.

In Python, a method is similar to a function except it is tied to an object. When we call a method on an object, it may or may not affect that object – in this situation, a set. It's worth noting that each operator corresponds to a distinct Python special function. So, they both accomplish the same thing but have distinct syntax requirements.

Python supports many set operations, including union, intersection, difference, and symmetric difference. Let us look at some examples of set operations in Python.

Python Union Operation With Example

The union of two sets is the set of all the elements, without duplicates, contained in either or both of the sets. In Python, you may use either the union() method or the | syntax to find the union. Let’s look at a Python union example.

Using the | operator:

# Defining the two sets
first_set = {1, 5, 7, 4, 5}
second_set = {4, 5, 6, 7, 8}

# Creating the union of the two sets
new_set = first_set | second_set

print(new_set) # Output: {1, 4, 5, 6, 7, 8}

Running the code above creates two sets: first_set and second_set. Then, the union operator creates a new_set with all unique elements from the first_set and the second_set.

The same is achieved using the union() method:

new_set = first_set.union(second_set)

Since the union consists of the elements of both sets, it is symmetric. So, first_set.union(second_set) results in the same set as second_set.union(first_set).

Python Intersection Operation With Example

The intersection of two sets is the set of all the elements that are common to both sets. In Python, you may use either the intersection() method or the & operator to find the intersection. Here are some Python intersection examples:

Using the & operator:

# Defining the two sets
first_set = {1, 5, 7, 4, 5}
second_set = {4, 5, 6, 7, 8}

# Creating the intersection of the two sets
new_set = first_set & second_set

print(new_set) # Output: {4, 5}

Running the code above creates two sets: first_set and second_set. Then, the intersection operator creates a new_set with all unique elements from the first_set and the second_set.

The same is achieved using the intersection() method:

new_set = first_set.intersection(second_set)

Since the intersection method produces a set of elements that are common to both sets, it is symmetric. So, first_set.intersection(second_set) results in the same set as second_set.intersection(first_set).

Python Set Difference Operation With Example

The difference between the two sets is the set of all the elements present in the first set but not in the second. Python lets you use either the difference() method or the - operator to do this. Let’s look at some examples of Python set differences.

Using the - operator:

# Defining the two sets
first_set = {1, 5, 7, 4, 5}
second_set = {4, 5, 6, 7, 8}

# Creating the difference of the two sets
new_set = first_set - second_set

print(new_set) # Output: {1, 2, 3}

You may also use the difference() method:

# Difference of two sets
# Initialize A and B
first_set = {1, 2, 3, 4, 5}
second_set = {4, 5, 6, 7, 8}

# Creating the difference between the two sets
new_set = second_set.difference(first_set)

print(new_set) # Output: {6, 7, 8}

As shown in the example, the difference operator is not symmetric. Which set you name first matters and influences the result of the new_set.

Make Use of Python Set Operations

In this tutorial, you have learned how to define set operations in Python. In addition, we have become familiar with the functions, operators, and methods used to work with sets. If you want to learn more about Python sets, e.g., how to get the symmetric difference, visit the article “Python Set Operations and More: All You Need to Know About Python Sets.”