how to get the intersection of two sets in python

To get the intersection of two sets in python, you can use the intersection() method or the & operator.

Here's an example using the intersection() method:

main.py
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {4, 5}
130 chars
5 lines

And here's an example using the & operator:

main.py
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
intersection_set = set1 & set2
print(intersection_set) # Output: {4, 5}
118 chars
5 lines

In both cases, the intersection_set variable will contain the intersection of both sets (i.e., the elements that are present in both of them).

gistlibby LogSnag