Back to articles list Articles
9 minutes read

Python Set Operations Explained With Examples

Having a hard time wrapping your head around set operations in Python? This article will help you visualize and understand Python set operations!

Python sets are useful data structures when you need to create and compare groups of elements. These tasks can be performed with set operations like union and intersection. However, using Python set operations may not be a straightforward task when you’re first starting out with Python itself.

In this article, we will explore examples of set operations in Python. When you’ve read it, be sure to check out the Python Basics: Part 3 course, which goes over all of the Python set operations you’ll see here – and well beyond that! The course is part of the Learn Programming with Python track, which is perfect for anyone looking to start their Python studies –  no previous programming experience required.

Let’s get started!

Quick Recap – How Do Python Sets Work?

Python sets represent a collection of values. In Python, we define a set by using curly braces and separating the elements with commas:

some_set = {3, 7, 15}

We can also use the set function to build a set from other data types, like lists:

some_list = [3, 7, 15]
some_set = set(some_list)

Python sets have specific properties: they are unordered, mutable containers that have unique elements in them. Here’s what these terms mean:

  • Being a container means that sets contain other elements in them. Lists and tuples are other examples of Python containers. If you’re confused by these terms, we have an article that clarifies the differences between lists, tuples, and sets.
  • Being unordered means that elements inside the set have no order. Sets do not have a “start” or an “end” position, nor can you ask for the “first” or “third” element in a set.
  • Being mutable means that elements can be added to or removed from sets. For example, you can start with an empty set and sequentially add elements to it.
  • Having unique elements means that sets can contain no duplicate elements. Duplicates are removed upon creating a set, and nothing happens if an element is added to a set that already has that same element in it.

Elements in a set do not need to have the same data type:

some_set = {"hey", 2.5, -10}

However, sets can only hold immutable elements. This means that mutable objects, like lists or dictionaries, cannot be placed inside sets. The code below throws an error because we attempt to create a set with a list inside:

bad_set = {'this will not work', [1, 2, 3]}  # raises a TypeError

Got all that? If you want a deeper dive in Python sets, we have an article giving you the full details on how sets work and how to create them.

Explaining Python Sets With Venn Diagrams

For all examples in this article, we will use the sets A and B, as depicted below:

Python Set Operations

Sets A and B will be used in our examples.

Note that A and B have some elements in common and some elements exclusive to each set. In Python code, we can represent these sets as follows (remember that the order of the elements does not matter):

A = {"good", 1, 17, 3.2, "hi"}
B = {17, 7.1, "good", -4, "Python"}

We can also represent A and B as a Venn diagram. This will be useful when visualizing the set operations later on. Here’s how it looks for now:

Python Set Operations

Venn diagram of A and B.

Python Set Union Example

Set union simply means combining all elements from the input sets into another set. As a Venn diagram, set union looks like the picture below. (Note: In our Venn diagrams, the returned areas will always be yellow.)

Python Set Operations

A set union combines all the elements of A and B.

In Python, we perform a set union by placing the | (vertical bar or “pipe”) operator between sets. See the example below:

A = {"good", 1, 17, 3.2, "hi"}
B = {17, 7.1, "good", -4, "Python"}

result = A | B
print(result)

# output: {1, 3.2, 'Python', 7.1, 'hi', 17, 'good', -4}

As expected, the set union operation combined all the elements from A and B into a single set.

Python set operations always return a new set, without modifying any of the input sets. This is why we need to save the resulting set in a variable (result in this example).

Note that the result set contains no duplicates, even though there were repeated elements in A and B. Its elements appear in no particular order. In fact, the order of the elements after executing the print(result) line would likely be different in your computer. These are expected consequences of the fact that sets are unordered sequences that contain no duplicate values – just like we discussed earlier!

Python Set Intersection Example

Set intersection means taking only the common elements from the input sets, i.e. the elements that appear both in A and B. This is the Venn diagram for a set intersection:

Python Set Operations

A set intersection returns only the elements that are common to A and B.

In Python, a set intersection is performed using the & (ampersand or “and”) operator. As with set union, you place the operator between the two sets to get their intersection. Here’s how it looks:

A = {"good", 1, 17, 3.2, "hi"}
B = {17, 7.1, "good", -4, "Python"}

result = A & B
print(result)

# output: {17, 'good'}

Notice how we got precisely the elements that were present in both A and B?

If the sets share no common elements, an empty set is returned:

fruits = {'orange', 'apple', 'melon'}
colors = {'green', 'red', 'blue'}

result = fruits & colors
print(result)

# output: set()

A useful set intersection application is to determine whether two sequences share at least one common element. With the set function, we can transform any sequences into sets (learn more about how to use Python’s set function here). We then use the set intersection to find out if at least one element is shared by all sets. Here’s an example:

students = ['John', 'Mark', 'Steve']
teachers = ['James', 'Rick', 'Albert']

students_set = set(students)
teachers_set = set(teachers)
name_intersection = students_set & teachers_set

if len(name_intersection) > 0:  # At least one element in intersection
	print('At least one student shares their name with a teacher')
else:
	print('No students share their names with teachers')

If we execute the code as-is, it prints the message telling us that no names are shared. If you edit the names in the students and teachers lists to include one common name, you will see the message change. And by the way, if you don’t understand what the if/else lines mean, we really recommend you check out our Python Basics Part 1 course!

Python Set Difference Example

A set difference is used to get elements that are present in one set but not the other. A key change from the previous operators is that the order of the sets matter: getting the elements of A that are not in B is not the same as getting the elements of B that are not in A! Below is the Venn diagram for both set difference operations for A and B:

Python Set Operations

Set differences between A and B.
The difference between A and B (left) is not the same as the difference between B and A (right)!

In Python, we use the - (minus) operator to denote set difference. For example:

A = {"good", 1, 17, 3.2, "hi"}
B = {17, 7.1, "good", -4, "Python"}

result_in_A = A - B
print(result_in_A)

# output: {1, 3.2, 'hi'}

result_in_B = B - A
print(result_in_B)

# output: {7.1, -4, 'Python'}

In a way, the Python set difference operator is intuitive: writing A - B means getting all elements present in A “minus” those also present in B. In any case, watch out when you use the set difference operator – you can accidentally write your expression in the wrong order!

Python Set Symmetric Difference Example

A set symmetric difference merges two previously seen Python set operations: set union and set intersection. The symmetric difference between A and B gets the elements that belong to either A or B (union), but excludes the elements shared by both sets (intersection). If this sounds a bit confusing, the Venn diagram below will help you out:

Python Set Operations

A set symmetric difference between A and B.
The only elements excluded are those that A and B have in common (i.e. their intersection).

Another way to think about a set symmetric difference is that it returns the opposite of whatever the set intersection would return. (Check out the Venn diagram for the set intersection to confirm this).

To perform the set symmetric difference operation in Python, we use the ^ (caret) operator:

A = {"good", 1, 17, 3.2, "hi"}
B = {17, 7.1, "good", -4, "Python"}

result = A ^ B
print(result)

# output: {-4, 1, 3.2, 7.1, 'Python', 'hi'}

Using Set Methods to Perform Python Set Operations

Up to this point, we used the operators below to perform Python set operations:

  • | for set union.
  • & for set intersection.
  • - for set difference.
  • ^ for set symmetric difference.

If you prefer, you can also perform these same operations using set methods. They are:

  • set.union() for set union.
  • set.intersection() for set intersection.
  • set.difference() for set difference.
  • set.symmetric_difference() for set symmetric difference.

To use these methods, you add a period after the variable that represents the first set, and write the method name. The second set is passed in as an argument to the method, inside parenthesis. If you were using the intersection() method, it would look something like this:

	set1.intersection(set2)

The code below performs all of the set operations we have previously seen, but it uses methods instead of operators:

A = {"good", 1, 17, 3.2, "hi"}
B = {17, 7.1, "good", -4, "Python"}

# Set union
union = A.union(B)
print(union)
# output: {1, 3.2, 'Python', 7.1, 'hi', 17, 'good', -4}

# Set intersection
intersection = A.intersection(B)
print(intersection)
# output: {17, 'good'}

# Set difference
diff_A = A.difference(B)
print(diff_A)
# output: {1, 3.2, 'hi'}
diff_B = B.difference(A)
print(diff_B)
# output: {7.1, -4, 'Python'}

# Set symmetric difference
sym_diff = A.symmetric_difference(B)
print(sym_diff)
# output: {-4, 1, 3.2, 7.1, 'Python', 'hi'}

If there are two ways to perform set operations in Python, which way should you use? It’s completely up to you. Some people prefer using set methods because the method name clearly indicates which operation is being applied to which set. On the other hand, those coming from a mathematical background may be more used to the symbolic representation of the Python set operators. Feel free to use whatever works best for you!

Want More Python Sets?

We went through some visual examples of Python set operators – but there’s more to learn! Go on over to the Python Basics: Part 3 course and try our interactive lessons and exercises. You’ll become a Python set operation master in no time!