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:
1 2 |
list1 = [1, 2, 3, 4, 5] list2 = [4, 5, 6, 7, 8] |
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.
1 2 |
set1 = set(list1) set2 = set(list2) |
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).
1 |
intersection = set1.intersection(set2) |
When you print the ‘intersection’ variable, you should get the output {4, 5}.
Full Code
1 2 3 4 5 6 |
list1 = [1, 2, 3, 4, 5] list2 = [4, 5, 6, 7, 8] set1 = set(list1) set2 = set(list2) intersection = set1.intersection(set2) print(intersection) |
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.