Table of Contents

Let’s take a look at how we can combine sets together to see what results we get! We’ll take a look at the three-set operations that allow us to put sets together – python set union, intersection, and difference – and we’ll even see what kind of results we get when we apply these operations to specific datasets. Before you know it, you’ll be set operations master! Let’s dive in. Using sets in Python can be extremely beneficial when dealing with large amounts of data, especially if you’re trying to filter it down and only keep the relevant information. This guide will cover all three set operations (union and intersection, and difference) and will provide examples to get you started using them in your own projects.

Get the latest updates on python programming in the Entri app

The set data structure in Python allows you to save unique values of any type and perform operations with them, such as combining or removing elements from the set. There are three common set operations in Python that can be performed using the & (intersection), (union), and – (difference) binary operators, respectively. In this article, we will look at the different use cases and examples of how to utilize these Python set operations to combine, remove, or obtain specific elements from sets.

To know more about python programming in the Entri app

**What Is a Set in Python?**

A set is a collection of unique items in Python. Sets are created with curly braces, or the set function. Items in a set are unordered, meaning they can’t be sorted or indexed. However, you can loop through a set just like any other collection. The set’s size (the number of items it contains) does not change as it goes through different operations. To get a specific item from a set, use square brackets. If there are multiple items with the same index in the list, each one will be returned by using an integer after it that corresponds to its position in the list (for example apple at index 0 would be returned as 0 apple). To delete an item from a set, use del followed by an index number or list-of-indexes within square brackets. For example, del 3 will delete the item at index 3; del 0 will delete all elements of that type in this set. To combine two sets into one set, use union, intersection, or difference. Union takes the union of both sets and creates a new set that includes all the members of both sets.

Enroll in our latest python programming course in the Entri app

Intersection takes the intersection of both sets and creates a new set containing only those members which exist in both sets. Difference takes only those members which exist in either but not both sets and creates a new set containing them. To create a subset of a set, put the indices for the subset between square brackets. For example: will create a subset of three integers from a set containing six integers. One way to demonstrate the differences between these operations is by creating a diagram. Let’s start with python set union: Here we have our set of numbers from 1-5. Let’s say we wanted to make our set include 9 as well, so we could do 9 5 . Note that the order doesn’t matter here because everything still needs to be unique. Next let’s take intersection: We have a more strict ordering requirement here because anything in our original set (1-5) has to also be included in our new set (1-3). So 1 2 3 would work, but 1 2 wouldn’t since 2 isn’t present in 1-5 when we’re looking for overlap on things outside the range of 1-3.

Get free placement assistance with the Entri app

**What Are Set Operations?**

In mathematics, a set is a collection of distinct objects, considered an object in its own right. Sets are one of the most fundamental concepts in mathematics and can be used to model situations in the real world. There are three main set operations: union and intersection, and difference. The union of two sets is the set that contains all elements that exist in either set but not both sets. The intersection of two sets is the set that contains only those elements that exist in both sets. The difference between two sets is the set that contains all elements present in one but not both sets. For example, given these two small lists from which we have removed duplicate elements (the elements found on both lists), we find their respective unions, intersections, and differences below

For example, 2 exists in only one of our two sets. However it is present in both sets’ difference.

Get the latest updates on python programming in the Entri app

This is because all three operations are disjoint—they do not share any members. The union of two sets with no shared members is a disjoint union—in other words, all members in either set or none at all. Similarly, if there are no shared members in the intersection of two sets then there will be nothing left over. The python set union of two sets may contain more than one member from each set if they have some commonality; however this may lead to duplication in the resulting list (such as when the first list has 3 unique items and 4 copies of 1 item). The difference of two sets may contain less than one member if they don’t share anything; however this may lead to empty results such as when one list has 4 unique items while another has 1 item.

Enroll in our latest python programming course in the Entri app

**The Unions of Sets**

The union of two sets is the set of all elements that are in either set. The union of {1, 2, 3} and {2, 3, 4} is {1, 2, 3, 4}. We can also write this as {1, 2, 3} ∪ {2, 3, 4} = {1, 2, 3, 4}. The symbol ∪ represents the union of two sets. The picture below shows the union of two sets as the shaded area. Notice how the areas inside both shapes (the blue rectangle and green circle) will be part of the union. The intersection of two sets is the set of all elements that are in both sets. For example, if we have {1, 2}, {3}, and {4}, then the intersection would be just one element: 3. As with unions, we can represent intersections with a vertical line ⋂ between two columns; for example, ⋂{1, 2}⋃{3}⋃{4}. The symbol ⋂ represents an intersection between two sets. A pictorial representation of an intersection would show only those points where lines from each shape overlap; for example, see the figure below. Finally, the difference of two sets is simply the set containing all elements in one set but not the other. The union of two sets is the set of all elements that are in either set. The intersection of two sets is the set of all elements that are in both sets.

Enroll in our latest python programming course in the Entri app

The difference between the two sets is the set of all elements that are in one set but not the other. In Python, these operations can be performed using the built-in set type. To get started, let’s define two sets: A and B. For example, if we had {1, 2} and {3}, then the difference would be just one element: 1. In math notation, it looks like this: {1} − {2}. It may seem confusing at first because this looks like subtraction when it’s really addition! But remember that when you do subtraction in math you need to subtract on both sides! So the set {1} − {2} is equivalent to {1} + (-2). Now let’s look at an example of union and intersection, and difference between these two sets:

A={10, 12}; B={14}; Union={10, 12}; Intersection={14}; Difference={12}; The three different types of set operations are shown in the following diagram. Unions, intersections, and differences form basic building blocks for more complicated functions such as sorting or graphing data.

Get the latest updates on python programming in the Entri app

**The Intersections of Sets**

Just as the name suggests, a python set intersection is where two sets intersect or overlap. The resulting set contains all of the elements that are common to both sets. In order to find the intersection of two sets, you’ll need to use the Python intersection method. This method takes two sets as input and returns a new set that contains only the elements that are common to both input sets. We can illustrate this with the following example: >>> mySet = {1, 2} >>> yourSet = {3, 4} >>> mySet.intersect(yourSet) {3, 4}

The difference between intersections and unions is that in unions each element appears at least once. For instance, if we have three sets A, B, and C with A={1}, B={2}, C={3}, then the union of these three sets would be {1, 2, 3}. On the other hand, intersections require at least one common element in each set before they will combine those elements into a new set. Let’s take a look at another example: >>> mySet = {1, 2} >>> yourSet = {3, 4} >>> mySet.intersect(yourSet) {3, 4}

Enroll in our latest python programming course in the Entri app

>>> ourUnion={1,2,3,4} # Note that the elements from yourSet are duplicated (e.g., 3).

>>> ourIntersection={1} # Note that the only shared element is 1 which has been combined with itself (e.g., 1). >>> ourDifference={3,4} # Note that there are no common elements so this set remains empty. It may seem redundant but I’m going to give an example using parentheses again just for illustration purposes. If we had two sets A={1} and B={2,3}, the union of these two sets would be A={1,2,3} while the python set intersection would be A={1}. Notice how in this last case both sets contain 1 but only one contains 2 and 3. As such it makes sense that the result is just 1.

The difference between intersections and unions is that in unions each element appears at least once.

Enroll in our latest python programming course in the Entri app

**The Differences Between Sets**

In set theory, two sets are equal if they have the same elements. That is, two sets A and B are equal if every element of A is also an element of B, and vice versa. The intersection of two sets A and B is the set of all elements that are both in A and in B. The union of two sets A and B is the set of all elements that are either in A or in B. It may seem like there’s a lot of overlap between these three operations but with small changes you can create very different outputs from your inputs.

For example, take these four sets: {a}, {b}, {c}, and {d}. These sets are not equal because each one has a different number of elements. We can use Python’s set operators to find their python set intersection, unions, and differences . Let’s start by calculating the union for these four sets using this code:

Enroll in our latest python programming course in the Entri app

First we import pandas as pd, then we define our list of 4 sets (sets1) as a variable setlist. Next we define our output (set1_union) as a list object by setting it equal to . Then we iterate through our list setlist and add the values in any set containing more than 1 value into our new list set1_union. Once finished iterating through setlist, we print out the contents of set1_union which contains 17 items. Now let’s calculate the difference of these four sets using this code:

First we import pandas as pd, then we define our list of 4 sets (sets2) as a variable setlist. Next we define our output (set2_difference) as a list object by setting it equal to . Then we iterate through our list setlist and subtract the values in any set containing more than 1 value from our new list set2_difference.

Once finished iterating through setlist, we print out the contents of set2_difference which contains 7 items.

Get the latest updates on python programming in the Entri app

**Conclusion**

Operations between sets are a fundamental part of many mathematical applications. In Python, the built-in set type implements these operations as well as many others. This tutorial explained how to use the union, intersection, and difference operators on sets in Python. With this knowledge in hand, you can start using sets in your own programs to solve all sorts of interesting problems. You should be able to figure out most of the other functions by reading their documentation or trying them out for yourself! Have fun learning about new ways to combine and divide data sets with Python’s powerful set operations. If you are interested to learn new coding skills, the Entri app will help you to acquire them very easily. Entri app is following a structural study plan so that the students can learn very easily. If you don’t have a coding background, it won’t be a problem. You can download the Entri app from the google play store and enroll in your favorite course.

Get the latest updates on python programming in the Entri app

## Discussion about this post