# 7 Ways to Achieve List Intersection in Python

List is a data type in python which is used to store multiple items. Lists are very versatile because they can store items of multiple types such as integer, string, float, etc. They are mutable, and commas separate their elements. The elements inside a list can be accessed with the help of indexing. In this article, we will be looking into several ways to perform python list intersection.

Contents

## 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

## 1. Using the Intersection() function

Intersection() is a pre-defined function in python used to perform intersection between two elements of a set. It returns a new set with the common values from the input sets. For this, we have to convert the list to set explicitly.

Let us take the following two lists, A and B. Then, we shall use set() to convert A and B from lists to sets. After the conversion, set(A) will call the intersection() method, where the set(B) would be passed as an argument to the function. Then, we will use list() to convert the obtained set output into a list. The intersected list will be saved into a variable named ‘intersect’.

```A = [0,1,10,5,8]
B = [7,1,3,11,0]
intersect = list(set(A).intersection(set(B)))
print(intersect)
```

The Output is:

`[0, 1]`

## 2. Applying & between sets

Another way of performing python list intersection is by converting the lists into sets and then applying & between the two sets. This will return the common elements from both sets. We can explicitly convert both sets into lists.

Let us take the following example:

We have first applied set() on the lists A and B. Then, we apply the and operand & between the two sets. We have explicitly converted it into list type using list() and saved it into a variable named ‘intersect’ to the set output.

```A = [0,1,10,5,8]
B = [7,1,3,11,0]
intersect = list(set(A) & set(B))
print(intersect)
```

On printing ‘intersect’, the output is:

```[0, 1]
```

## 3. Using list comprehension

We can also perform list intersection using list comprehension. List comprehension provides a compact syntax for creating a new list using an already existing list.

Here, inside the statement ‘i for i in A if i in B’, we want to append element ‘i’ inside our list ‘intersect’ for every element in ‘A’, if the same element exists in ‘B’. The element will be added to the list only if it fulfills the given condition. Else, the element will be discarded.

```A = [0,1,10,5,8]
B = [7,1,3,11,0]
intersect = [i for i in A if i in B]
print(intersect)
```

The output list ‘intersect’ is:

`[0, 1]`

## 4. Using filter and lambda

Filter in python is an inbuilt function that is used to filter out elements from a given list. We pass each element from the list to the given function. Only those elements will be included for which the function returns True value.

Lambda is an anonymous function that only contains a single line expression. We will be using both filter and lambda to perform intersection between two lists. First, inside we have a lambda function where we return the common elements. And for all the true values, the filter will only include those values in the list ‘intersect’.

```A = [0,1,10,5,8]
B = [7,1,3,11,0]
intersect = list(filter(lambda x:x in A,B))
print(intersect)
```

The output is:

`[1, 0]`

## 5. With numpy.intersect1d() function

We can also use the intersect1d() function present in the numpy library to achieve a list intersection. We will pass two lists as arguments, and it will return the unique values from both lists in a sorted manner. The output will then be explicitly converted to a list using the list() function.

The example is :

```import numpy as np
A = [0,1,10,5,8]
B = [7,1,3,11,0]
intersect = list(np.intersect1d(A, B))
print(intersect)
```

Output:

`[0, 1]`

## 6. Creating a user defined function

We can also build a user-defined function for performing intersection. If an element exists in list1, we will append that element in a new list ‘intersect’ if it is present in list2 too. We achieve this using for loop and if statement. The function will then print the list ‘intersect’.

The code for the function is:

```def intersect(list1, list2):
intersect = []
for i in list1:
if i in list2:
intersect.append(i)
print(intersect)

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

intersect(A,B)
```

The output is:

`[0, 1]`

## 7. Using Collections Counter

A counter is a container that keeps track of the frequency of each element in the container. We shall have to import Counter from collections. The code to do so is:

```from collections import Counter
A = Counter([0,1,10,5,8])
B = Counter([7,1,3,11,0])
A &= B
intersect = list(A.elements())
print(intersect)
```

The output is:

```[0, 1]
```

## List intersection in multi-dimensional lists

To perform intersection for lists of dimensions more than one, we can make use of reduce() function. Reduce() is used to apply a function to an iterable and then reduce it to a single value.

For using reduce, we will import it from functools. Here, we have taken a two-dimensional list A. We shall use the intersection() function inside reduce() and convert each sub-list into a set. Then, we shall be comparing each set with another and keep only the common unique values. In the end, reduce() will keep only the common values. We shall convert it into a list using list() and print the list.

```from functools import reduce
A = [[0,6,3,2],[7,0,1,6], [6,7,10,0]]

intersect = list(reduce(set.intersection, [set(x) for x in A ]))

print(intersect)
```

The output is:

``[0, 6]``

## FAQ’s on Python List Intersection

How to avoid duplicate values in list intersection?

To avoid duplicate values inside the list intersection we can make use of the set methods. By converting the list into a set and then performing the intersection would avoid the duplicate values from being included in the intersection. This is because the set does not store any duplicate values.

That wraps up the python list intersection. If you have any questions in mind, leave them below in the comments.

Until next time, Keep Learning!

Subscribe
Notify of 