Like mathematics, we can also find the intersections of the set in Python. It provides tools to the perform set intersection and generates a completely new set as the output. In this article, we will study how to find set intersections in Python along with examples and output. We will learn the different methods to do the same and learn how to coden them.

**What is a Set Intersection?**

**Python sets are one of the most fundamental data structures which enable you to store the elements in sequential form. **The data elements in sets are represented inside the curly brackets, and commas separate each element. **Sets are unordered, unchangeable, and unindexed, which means you can remove the set element and add new elements but cannot change the elements already present in the set. **

**The intersection of two sets can be defined as the formation of a new set containing the common elements of both the given sets.** Set intersection is not a constraint between two sets, and therefore, you can have as many sets as you want to find the common elements between them. Suppose the intersection of set A and set B is a set containing all the elements present in set A and set B.

The below image shows the Venn diagram of set intersections, i.e., representing the common elements from both sets. The Apple is common between both the sets, so we will get it as an output for this intersection.

Now you know what we mean by set intersection, let's learn how to find it.

**How to Find the Intersection of Sets in Python?**

We will learn about different ways to get the intersection of two sets in Python programming:

**1) Using intersection() Function**

**Python's intersection() function is an in-built method by which you can perform the set intersection that enables you to identify the elements that are shared by two or more sets.** The intersection() function does not alter the initial sets, but a new set comprising the shared components of the intersecting sets is returned.

The syntax of the intersection function is given below:

set A.intersection(set B, set C, set D, …)

Here, the intersection method takes a parameter as the set variable for which the common element is found. It returns as the new set containing the common elements of all the sets(set B, set C, set D…). Check out the below example to understand the working of the intersection() method. For example:

X = {1, 3, 5, 7} Y = {2, 3, 5, 8} print(X.intersection(Y))

**Output:**

`{3, 5}`

The intersection() function in Python has a temporal complexity of O(min(len(set1), len(set2))), where set1 & set2 are the sets that are being intersected. This indicates that the time needed to complete the intersection operation grows linearly as the smaller set's size does.

**2) Using intersection operator(&)**

Apart from the Python inbuilt function, you can also perform set intersection using the intersection operator. **The ampersand symbol (&) is used to symbolize the Python Set Intersection symbol, and is employed to perform an intersection operation between two or more sets.**

Here, the operator is placed between both sets and as a result, the completely new set is formed as the output containing the common elements of sets. For example:

X = {1, 3, 5, 7, 8} Y = {2, 3, 5, 8} Z = {0, 2, 4, 8} print(X & Y) print(Y & Z) print(X & Y & Z)

**Output:**

{8, 3, 5} {8, 2} {8}

In this example, we use the & operator to first find the intersection between X and Y, then between Y and Z, and finally between all three of them.

**3) Using empty set for set intersection**

Set intersection returns the common elements of any two sets, but what if the sets are empty and do not contain any elements in them? **The output after performing the intersection will also be an empty set as there are no common elements in the given sets.** For example:

X = {} Y = {} print(set(X).intersection(set(Y)))

**Output:**

```
set()
```

**4) Python Intersection of Multiple Sets**

The & operator or the intersection() method in Python can be used to execute an intersection of multiple sets. The intersection() method is employed to perform an intersection of many sets, whereas the & operator is employed to perform an intersection of two sets.

Utilizing the intersection() method, we may execute an intersection of multiple sets by passing the sets as arguments, as demonstrated in the example below:

# Create three sets set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} set3 = {5, 6, 7, 8, 9} # Perform intersection of multiple sets intersection = set1.intersection(set2, set3) # Print the intersection print(intersection)

**Output:**

{1,2,3,4,5,6,7,8,9,10,11,12,13}

In the aforementioned example, we produced sets 1, 2, and 3. The intersection of all three sets was then calculated using the intersection() method, and the outcome was saved in the intersection variable. The common elements that exist in all the sets getting intersected are contained in the new set that is returned by the intersection() method.

The intersection set's contents, which include the elements shared by all three sets, were then printed.

If we have a lot of sets, we can also send them as a variable-length input list using the intersection() method and the * operator. For instance:

# Create five sets set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} set3 = {5, 6, 7, 8, 9} set4 = {8, 9, 10, 11, 12} set5 = {9, 10, 11, 12, 13} # Perform intersection of multiple sets intersection = set1.intersection(set2, set3, set4, set5) # Print the intersection print(intersection)

**Output:**

{1,2,3,4,5,6,7,8,9,10,11,12,13}

In this instance, we made five sets: Sets 1, 2, 3, 4, and 5. After that, we performed an intersection operation among each of the five sets using the intersection() function and the * operator, and we saved the outcome in the intersection variable. The common elements present in each of the sets being intersected are contained in the new set that is returned by the intersection() method.

The intersection set's contents, which include the elements shared by all five sets, were then printed.

**Set intersection() Method vs Set Intersection Operator (&)**

**To find the set intersection, the intersection() method accepts any iterable such as lists, strings, and dictionaries, etc. However, the set intersection operator only allows a set data structure to find the intersection.**

As the intersection method accepts any iterable, note that it will convert every iterable to a set before intersecting them and generating the output accordingly. For example:

X = {1, 3, 5} Y = [1, 5, 9] result = X.intersection(Y) print(result)

**Output:**

```
{1, 5}
```

In the above example, the intersection is performed between a set and a list; however, the intersection method converted the list to a set internally and generates the output. At the same time, the intersection operator will not accept any iterable and hence raise the error if you use them. Look at the code below:

X = {1, 2, 3} Y = [2, 3, 4] result = X & Y print(result)

**Output:**

```
TypeError: unsupported operand type(s) for &: 'set' and 'list'
```

## Common Set Intersection Issues and Troubleshooting them

While set intersection can be straightforward, some common issues may arise during its use. Understanding and addressing these issues can help you avoid potential pitfalls.

### Dealing with Unhashable Items

In Python, sets only support hashable or immutable items. If you attempt to create a set with unhashable items, such as lists or dictionaries, a TypeError will occur. To resolve this issue, you can convert unhashable items into hashable ones. For example, you can convert a list into a tuple, which is hashable:

set1 = {(1, 2, 3)} print(set1) # Output: {(1, 2, 3)}

In this example, we convert the list (1, 2, 3) into a tuple (1, 2, 3) to make it hashable and then include it in the set.

### Handling Mutable Sets

Another common issue arises when attempting to use mutable sets or set objects as items in another set. Since set objects are mutable, they are unhashable and cannot be included in other sets. However, Python provides the frozenset data type, which is an immutable version of a set. Here's an example:

set1 = {frozenset({1, 2, 3})} print(set1) # Output: {frozenset({1, 2, 3})}

In this example, we create a frozenset from a set and include it in another set. The frozenset allows us to include sets as items in other sets.

By understanding and addressing these common issues, you can work with set intersection effectively in Python.

Also, learn how to find set differences in Python to understand and complete both these concepts at once.

**Summary**

Python sets are the most fundamental data structure used to store sequential data into a single variable. Set intersection is a fundamental operation in Python that allows you to find common elements among sets. By using either the intersection() method or the & operator, you can efficiently determine common elements and perform various set operations. Remember to choose the method that best suits your coding style and consider exploring other set operations to further enhance your Python programming skills.