Javatpoint Logo
Javatpoint Logo

Python Program to Find Intersection of Two Lists

In this tutorial, we will discuss how we can get the intersection of the two lists. The intersection of two lists means we need to get all the familiar elements to both of the initial lists.

Python is known for its excellent built-in data structure. Python list is one of the famous and valuable built-in data types of Python. It can store the various data-types value in sorted order. However, there is no built-in function for lists like sets.

Python provides the many ways to perform the intersection of the lists. Let's see the following scenario.

Input :

Output:

[90, 11, 58, 31, 66, 28, 54]

Input :

Output:

[9, 11, 26, 28]

Let's see following methods to get intersection of two lists.

Method - 1: Using for loop

Output:

[90, 11, 58, 31, 66, 28, 54]

We have used for loop to get the common value from both lists and stored it in the list3 variable.

Method - 2: Convert List to Set

Output:

[66, 90, 11, 54, 58, 28, 31]

Method - 3:

We will use the built-in set's intersection() method. The intersection() is a first-class part of the set. Let's understand the following example.

Example -

Output:

{66, 90, 11, 54, 58, 28, 31}

Method - 4:

In this method, we will use the hybrid method. This is much efficient way to perform the task. Let's understand the following example.

Example -

Output:

[90, 11, 58, 31, 66, 28, 54]

Method - 5:

In this method, we will use the filter() method. The intersection is performed over sub-lists inside other lists. Let's understand the following example.

Example -

Output:

[[17, 23, 40], [10], [60]]

The filter() method takes each item of the sublist and checks if it is present in the list1. The list comprehension is executed for each sublist in the list2.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback

  • Send your Feedback to feedback@javatpoint.com

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA