Find common elements in list of lists in Python

PythonServer Side ProgrammingProgramming

It is possible to have a list whose inner elements are also lists. In such cases we may come across a need when we have to find out the common elements among these inner lists. In this article we will find out the approaches to achieve this.

With map and intersection

Intersection is a simple mathematical concept of finding the common elements between different sets. Python has the set method which returns a set that contains the similarity between two or more sets. So we first convert the elements of the list into set through a map function and then apply the set method to all this converted lists.

Example

 Live Demo

listA = [['Mon', 3, 'Tue', 7,'Wed',4],['Thu', 5,'Fri',11,'Tue', 7],['Wed', 9, 'Tue', 7,'Wed',6]]

# Given list
print("Given list of lists : \n",listA)

# Applying intersection
res = list(set.intersection(*map(set, listA)))

# Result
print("The common elements among inners lists : ",res)

Output

Running the above code gives us the following result −

Given list of lists :
[['Mon', 3, 'Tue', 7, 'Wed', 4], ['Thu', 5, 'Fri', 11, 'Tue', 7], ['Wed', 9, 'Tue', 7, 'Wed', 6]]
The common elements among inners lists : ['Tue', 7]

With reduce and lambda

We can also apply the reduce function in python. This function is used to apply a given function passed onto it as argument to all of the list elements mentioned in the sequence passed along. The lambda function finds out the common elements by iterating through each nested list after set is applied to them .

Example

 Live Demo

from functools import reduce
listA = [['Mon', 3, 'Tue', 7,'Wed',4],['Thu', 5,'Fri',11,'Tue', 7],['Wed', 9, 'Tue', 7,'Wed',6]]

# Given list
print("Given list of lists : \n",listA)

# Applying reduce
res = list(reduce(lambda i, j: i & j, (set(n) for n in listA)))

# Result
print("The common elements among inners lists : ",res)

Output

Running the above code gives us the following result −

Given list of lists :
[['Mon', 3, 'Tue', 7, 'Wed', 4], ['Thu', 5, 'Fri', 11, 'Tue', 7], ['Wed', 9, 'Tue', 7, 'Wed', 6]]
The common elements among inners lists : ['Tue', 7]
raja
Published on 13-May-2020 14:53:11
Advertisements