Set Operations
- 03:08
Learn how to perform union, intersection, and difference operations between sets in Python.
Downloads
No associated resources to download.
Transcript
Now that you're familiar with what a set is, we're going to look at three different operations that you can perform between sets. Union, Intersection and Difference. And for each of these you're going to use the format set one dot function, the name of the function, and then in parentheses the name of set two. So let's take a look at what this actually looks like. First I'm gonna start by defining these two sets. So I have a set of companies with Market Cap over 500 billion, and then I have a set of companies which are AAA rated by Moody's. I'm gonna execute that cell and define those sets. Now I'm gonna combine them using union and the order which set is set one and which set is set two does not matter. You're going to get the same answer either way. So I'm gonna say print market cap, over 500 dot union, and then the name of my second set, AAA A rated.
And just to show you, I'm gonna also swap these around. I guess I'll create a new cell and I'll change the order just to show you that you're gonna get the same answer either way.
And there you go. Next we're going to look at intersection. And intersection finds the common elements between two sets, similar to union, the order that you put the sets in, doesn't matter. You're gonna get the same answer either way. So let's give that a shot and you're gonna see that the only value in common between these two sets is Microsoft. The third function we're gonna look at is the difference function. And here order does matter. Let's take a look at how that works.
So market cap over 500. And then the difference between that and AAA rated, you're gonna see that we're looking at what market cap has that Triple A rated does not have. Because market cap is first, we're going to print out the unique values in market cap that are not included in triple A rated. If I do the other side of that, you're gonna see that I'm gonna keep the unique values in AAA rated that are not in the set market cap over 500. So when you're looking at union order doesn't matter. When you're looking at intersection order does not matter. But when you're looking at difference, it's gonna give you the values in the first set that are not included in the second set.