How do you find the point of intersection of two lists in Python?

Python | Intersection of two lists

Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list. Now there are various ways in Python, through which we can perform the Intersection of the lists.
Examples:

Input : lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9] lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87] Output : [9, 10, 4, 5] Input : lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69] lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26] Output : [9, 11, 26, 28]

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Method 1:
This is the simplest method where we haven’t used any built-in functions.




# Python program to illustrate the intersection

# of two lists in most simple way

def intersection(lst1, lst2):

lst3 = [value for value in lst1 if value in lst2]

return lst3

# Driver Code

lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]

lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]

print(intersection(lst1, lst2))

Output:

[9, 11, 26, 28]

Method 2:
This method includes the use of set() method.






# Python program to illustrate the intersection

# of two lists using set() method

def intersection(lst1, lst2):

return list(set(lst1) & set(lst2))

# Driver Code

lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]

lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]

print(intersection(lst1, lst2))

Output:

[9, 10, 4, 5]

Method 3:
In this method we set() the larger list and then use the built-in function called intersection() to compute the intersected list. intersection() is a first-class part of set.




# Python program to illustrate the intersection

# of two lists using set() and intersection()

def Intersection(lst1, lst2):

return set(lst1).intersection(lst2)

# Driver Code

lst1 = [ 4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]

lst2 = [9, 9, 74, 21, 45, 11, 63]

print(Intersection(lst1, lst2))

Output:

{9, 11}

Method 4:
By the use of this hybrid method the complexity of the program falls to O(n). This is an efficient way of doing the following program.




# Python program to illustrate the intersection

# of two lists

def intersection(lst1, lst2):

# Use of hybrid method

temp = set(lst2)

lst3 = [value for value in lst1 if value in temp]

return lst3

# Driver Code

lst1 = [9, 9, 74, 21, 45, 11, 63]

lst2 = [4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]

print(intersection(lst1, lst2))

Output:

[9, 9, 11]

Method 5:
This is the where the intersection is performed over sub-lists inside other lists. Here we have used the concept of filter().




# Python program to illustrate the intersection

# of two lists, sublists and use of filter()

def intersection(lst1, lst2):

lst3 = [list(filter(lambda x: x in lst1, sublist)) for sublist in lst2]

return lst3

# Driver Code

lst1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]

lst2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]

print(intersection(lst1, lst2))

Working: The filter part takes each sublist’s item and checks to see if it is in the source list. The list comprehension is executed for each sublist in list2.
Output:

[[13, 32], [7, 13, 28], [1, 6]]

How do you find the point of intersection of two lists in Python?




Article Tags :

Python

Python list-programs

python-list

Practice Tags :

python-list

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.


Next TopicHow to Create Requirements.txt File in Python



← prev next →



What is intersection?

An intersection in python can be performed between two or more lists or sets. With intersection, we get the common elements present in all the lists, i.e., it returns the elements which exist in all the lists.

Example : If we have two lists – A and B containing the following elements:

A = [0,1,10,5,8] B = [7,1,3,11,0]

Then here, there are only two common elements from both the list – 0 and 1. Therefore, the intersection between the two lists would be 0 and 1.

Performing Python List Intersection

Now, we shall look into some methods of intersecting lists in python:

  1. Using the intersection() function
  2. Applying & between sets
  3. Using list comprehension
  4. With filter and lambda
  5. Using numpy.intersect1d() function
  6. Creating a user-defined function
  7. Using Collections Counter

Find the intersection of two lists in Python

In this post, you will learn different ways to find the intersection of two lists in Python. The intersection of two lists contains the elements that the two lists have in common. The returned list contains only items that exist in both lists, or in all lists, if the comparison is done with more than two lists. There are various ways through which we can perform the intersection of two lists. Here we have mentioned most of them -



Using sets to find intersection of two lists in Python

The first method to find the intersection of two lists in Python is to convert the lists to sets and use either the & operator or the built-in intersection() method.

But first, what is a set?

A set is similar to a list, in that it can be used to store a collection of items (such as a collection of numbers).

For instance, we can create a set to store the numbers 1, 22, 43, 64 and 57.

To do that, we use curly braces, as shown in the example below:

mySet = {1, 22, 43, 64, 57}

As you can see, creating a set is very similar to creating a list, except that the former uses curly braces while the latter uses square brackets.

A set is indeed very similar to a list. However, there are a few key differences between them, as explained in the table below:

Key differences between a set and a list

ListSet
Items are ordered (i.e. the order of the items is important).

Hence, [1, 2, 3, 4] and [2, 3, 1, 4] are considered to be two different lists

Items are not ordered (i.e. the order of the items is disregarded).

Hence, {1, 2, 3, 4} and {2, 3, 1, 4} are considered to be the same set

Items need not be distinct.

[1, 1, 1, 2, 3] is all right

Items must be distinct.

{1, 1, 1, 2, 3} gives us an error as the number 1 appears more than once in the set

Items need not be hashable*Items must be hashable*

Examples of items that are hashable include integers, floating-point numbers and strings.

Examples of items that are not hashable include nested lists or dictionaries

  • Hashable items refer to items that have a hash value which never changes during its lifetime. A full discussion of this is beyond the scope of this tutorial. If you are interested, you can check out the official documentation at https://docs.python.org/3/glossary.html#term-hashable.

To find the intersection of two lists in Python, we can convert the lists to sets and use the built-in & operator or the intersection() method.

Let’s look at some examples:

Converting lists to sets and using the & operator

list1 = [1, 2, 3, 4, 5] list2 = [3, 4, 5, 6, 7] set1 = set(list1) set2 = set(list2) intersect = list(set1 & set2) print(intersect)

Here, we first declare two lists – list1 and list2 – on lines 1 and 2.

Next, on lines 4 and 5, we use the set() function to convert the lists to sets.

On line 7, we use the & operator to find the intersection between the two sets. This operator returns a new set with elements common to both set1 and set2. We pass this resulting set to the list() function to convert it back to a list and assign the resulting list to intersect.

Finally, we print the value of intersect on line 9.

If you run the code above, you’ll get the following output:

[3, 4, 5]

Converting lists to sets and using the intersection() method

Next, let’s look at an example that uses the intersection() method.

While the & operator can only be used on two sets, the intersection() method can be used with other types of iterables, such as a list or tuple.

Its syntax is as follows:

<name of set>.intersection(<names of interables>)

Let’s look at an example:

list1 = [1, 2, 3, 4, 5] list2 = [3, 4, 5, 6, 7] set1 = set(list1) intersect = list(set1.intersection(list2)) print(intersect)

Here, we only convert list1 to a set. This is because we can pass a list (e.g. list2) directly to the intersection() method, without having to convert the list to a set.

We do that on line 6, where we use set1 to call the intersection() method and pass list2 as an argument to the method.

This method returns a set. We convert the set back to a list using the list() function, and assign the result to intersect.

Finally, we print the value of intersect on line 8.

If you run the code above, you’ll get the following output:

[3, 4, 5]

Error in converting lists to sets

Last but not least, let’s look at an example where we are unable to convert a list to a set. That happens when one or more of the items in the list is not hashable. For instance, if the list has a nested list (which is not hashable), we’ll get an error when we try to convert the list to a set.

list1 = [1, 2, 3, 4, 5, [7, 8, 9]] set1 = set(list1)

If you run the code above, you’ll get the following error:

Traceback (most recent call last): File "...", line ..., in <module> set1 = set(list1) TypeError: unhashable type: 'list'

Using a Python For Loop to Find Intersection Between Two Lists

Using a Python for loop is an easy, intuitive way to find the intersection between two lists. The benefit of understandability here comes at a performance hit with lists of much larger sizes.

What we’ll do, is loop over each item in a list and see if it exists in the other. If it does, then we append it to a new list. If it doesn’t, then we’ll do nothing.

Let’s take a look at what this code would look like:

# Find intesection between two Python lists using a for loop list1 = ['a', 'b', 'c', 'd', 'e'] list2 = ['b', 'd', 'e', 'f', 'g'] intersection = list() for item in list1: if item in list2: intersection.append(item) print(intersection) # Returns: ['b', 'd', 'e']

In the next section, you’ll learn how to turn this for loop into a Python list comprehension.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Using List Comprehensions to find the Intersection Between Two Python Lists

In many cases, a Python for loop can be turned into a list comprehension. The benefit of doing this is the ease of coding it out. Python list comprehensions comes with some key benefits:

  1. You don’t need to instantiate a new, empty list
  2. The code generally only spans a single line, rather than multiple lines

Essentially, the algorithm we’ll follow is the same as the for loop: we loop over each item and see if it exists in the other list. If it does, then we add it to our new list.

Let’s see what this would look like in Python:

# Find intesection between two Python lists using a list comprehension list1 = ['a', 'b', 'c', 'd', 'e'] list2 = ['b', 'd', 'e', 'f', 'g'] intersection = [item for item in list1 if item in list2] print(intersection) # Returns: ['b', 'd', 'e']

Similar to the for loop method, as your list sizes grow, this can encounter some performance hiccups. This is where the next method comes into play. In the next section, you’ll learn how to use Python set methods to find the intersection between two lists.

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

How to find the intersection of two list elements in python

How do you find the point of intersection of two lists in Python?