📜  python interseciton of 2 sets - Python (1)

📅  最后修改于: 2023-12-03 15:04:05.679000             🧑  作者: Mango

Python Intersection of 2 Sets

In Python, we can find the intersection of two sets using the intersection() method.

The intersection method returns a new set that contains elements that are common to both sets.

Here's an example:

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

intersection_set = set1.intersection(set2)

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

In this example, we have two sets - set1 and set2. We use the intersection() method to find the common elements in both sets and store the result in the intersection_set variable. Finally, we print the intersection_set variable, which contains the common elements {4, 5}.

We can also use the & operator to find the intersection of two sets like this:

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

intersection_set = set1 & set2

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

In this example, we use the & operator to find the intersection of set1 and set2. The result is the same as the previous example, {4, 5}.

It's important to note that the intersection() method and & operator return a new set and do not modify the original sets.

We can also find the intersection of more than two sets by applying the intersection() method or & operator to all sets. Here's an example:

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set3 = {3, 4, 5, 6}

intersection_set = set1.intersection(set2, set3)

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

intersection_set = set1 & set2 & set3

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

In this example, we have three sets - set1, set2, and set3. We use the intersection() method and & operator to find the common elements in all sets and store the result in the intersection_set variable. Finally, we print the intersection_set variable, which contains the common elements {4, 5}.

In conclusion, finding the intersection of two or more sets in Python is easy using the intersection() method or & operator. This can be useful for a variety of programming tasks, such as finding common elements in datasets or filtering out unwanted values.