Skip to main content

How to find the intersection of two lists in Python

How to find the intersection of two lists in Python.

Here's a step-by-step tutorial on how to find the intersection of two lists in Python:

1: Create two lists

First, let's create two lists that we want to find the intersection of. For example:

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

2: Use the set() function to convert the lists into sets

To find the intersection of two lists, we can convert them into sets using the set() function. Sets are an unordered collection of unique elements. This will help us easily find the common elements. For example:

set1 = set(list1)
set2 = set(list2)

3: Use the intersection operator (&) to find the common elements

Once we have converted the lists into sets, we can use the intersection operator (&) to find the common elements between the sets. For example:

intersection = set1 & set2

Alternatively, you can also use the intersection() method to achieve the same result:

intersection = set1.intersection(set2)

4: Convert the intersection set back to a list (if needed)

If you want the intersection result as a list instead of a set, you can convert it back using the list() function. For example:

intersection_list = list(intersection)

5: Print or use the intersection result

Finally, you can print or use the intersection result as per your requirements. For example:

print(intersection_list)

Here's the complete code:

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

set1 = set(list1)
set2 = set(list2)

intersection = set1 & set2

intersection_list = list(intersection)

print(intersection_list)

This will output [4, 5], which is the intersection of the two lists.

I hope this tutorial helps you find the intersection of two lists in Python! Let me know if you have any further questions.