How to Find the Intersection in Python

In today’s tutorial, we are going to learn how to find the intersection of two lists in Python. Intersection is a math term describing the shared elements of two or more sets. Working with data often involves comparing lists, and knowing how to identify the commonalities between these lists is a valuable skill in Python programming.

Step 1: Creating the Lists

Our first step is to create the lists that we are going to use to find our intersection. In Python, a list is created by placing items (elements) inside square brackets [], separated by commas.

Let’s create two lists:

Here, our lists have two common elements: 4 and 5.

Step 2: Using the built-in set() function

We can use the built-in function set() to convert our lists into sets. This function constructs a set object from any iterable. In Python, a set is a collection that is both unordered and unindexed, and it doesn’t allow duplicate values. This characteristic will be very useful to easily identify the intersection of two lists.

Step 3: Finding the Intersection

Python has a handy built-in method for sets called intersection(). This method returns the intersection of set1 and set2 (i.e., their common elements).

When you print the ‘intersection’ variable, you should get the output {4, 5}.

Full Code

Output

{4, 5}

Conclusion

Finding the intersection of two lists in Python is a common task in data analysis. Understanding how to use the set() function and the intersection() method is crucial for comparing datasets in Python.