Python | Find common elements in list of lists
Last Updated :
13 Mar, 2023
The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists. Let’s discuss certain ways in which this operation can be performed.
Method #1 : Using reduce() + lambda + set() This particular task can be achieved in just a one line using the combination of the above functions. The reduce function can be used to operate the function of “&” operation to all the list. The set function can be used to convert list into a set to remove repetition.
Python3
from functools import reduce
test_list = [[ 2 , 3 , 5 , 8 ], [ 2 , 6 , 7 , 3 ], [ 10 , 9 , 2 , 3 ]]
print ("The original list is : " + str (test_list))
res = list ( reduce ( lambda i, j: i & j, ( set (x) for x in test_list)))
print ("The common elements from N lists : " + str (res))
|
Output:
The original list is : [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
The common elements from N lists : [2, 3]
Time complexity: O(n*m*log(m)), where n is the number of lists and m is the maximum length of a list.
Auxiliary space: O(m), where m is the maximum length of a list.
Method #2: Using map() + intersection() The map function can be used to convert each of the lists to set to be operated by to perform the intersection, using the set.intersection function. This is the most elegant way to perform this particular task.
Python3
test_list = [[ 2 , 3 , 5 , 8 ], [ 2 , 6 , 7 , 3 ], [ 10 , 9 , 2 , 3 ]]
print ("The original list is : " + str (test_list))
res = list ( set .intersection( * map ( set , test_list)))
print ("The common elements from N lists : " + str (res))
|
Output:
The original list is : [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
The common elements from N lists : [2, 3]
Time complexity: O(N*M), where N is the number of lists and M is the average length of each list.
Auxiliary space: O(M), where M is the maximum length of any list
Method #3 : Using itertools
Here is another approach that could be used to find the common elements in a list of lists. This approach involves using the itertools module’s product function to create a list of all possible pairs of elements from the lists, and then using a list comprehension to filter this list down to only the pairs where the elements are equal. This approach has a time complexity of O(n^2) and a space complexity of O(n^2), as it requires generating a list of all possible pairs of elements and then filtering this list down to only the common elements.
Here is an example of how this approach could be implemented in Python:
Python3
test_list = [[ 2 , 3 , 5 , 8 ], [ 2 , 6 , 7 , 3 ], [ 10 , 9 , 2 , 3 ]]
print ( "The original list is:" , test_list)
import itertools
pairs = list (itertools.product( * test_list))
common_elements = set ([x[ 0 ] for x in pairs if x[ 0 ] = = x[ 1 ] and x[ 0 ] = = x[ 2 ]])
print ( "The common elements are:" , common_elements)
|
Output
The original list is: [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
The common elements are: {2, 3}
The time complexity of the above code to find the common elements in a list of lists is O(n^2), where n is the total number of elements in all the sublists combined.
The space complexity of the code is O(n), where n is the total number of elements in all the sublists combined.
Method #4: Using list comprehension and set intersection
Use list comprehension and set intersection to find the common elements from N lists.
Python3
test_list = [[ 2 , 3 , 5 , 8 ], [ 2 , 6 , 7 , 3 ], [ 10 , 9 , 2 , 3 ]]
print ( "The original list is : " + str (test_list))
res = list ( set (test_list[ 0 ]).intersection( * test_list[ 1 :]))
print ( "The common elements from N lists : " + str (res))
|
Output
The original list is : [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
The common elements from N lists : [2, 3]
Time Complexity: O(n * k) where n is the number of lists and k is the maximum length of the lists.
Auxiliary Space: O(k) where k is the maximum length of the lists.
Method #5: Using a loop to compare each element in the first list with the other lists
This method iterates through each element in the first list and checks if it exists in all the other lists using a loop and the all() function. If an element exists in all the other lists, it is added to the common_elements list.
Python3
test_list = [[ 2 , 3 , 5 , 8 ], [ 2 , 6 , 7 , 3 ], [ 10 , 9 , 2 , 3 ]]
common_elements = []
for element in test_list[ 0 ]:
if all (element in sublist for sublist in test_list[ 1 :]):
common_elements.append(element)
print ( "The common elements from N lists : " + str (common_elements))
|
Output
The common elements from N lists : [2, 3]
The time complexity of the above code is O(n*m^2), where n is the length of the first sublist and m is the number of sublists in the test_list.
The auxiliary space complexity of the code is O(k), where k is the number of common elements in all the sublists.
Similar Reads
Uncommon Elements in Lists of List - Python
We are given two lists of lists and our task is to find the sublists that are uncommon between them. (a sublist is considered uncommon if it appears in only one of the lists and not in both.) For example: a = [[1, 2], [3, 4], [5, 6]] and b = [[3, 4], [5, 7], [1, 2]] then the output will be [[5, 6],
4 min read
Find Most Common Element in Each Column in a 2D List - Python
We are given a matrix named m= m = [[1, 2, 3], [4, 2, 3],[1, 5, 3],[4, 2, 6]] we need to count the most common element in each column in the matrix we so that the output in this case will be [1,2,3]. We can do this by using multiple function like Counter from colleciton library and defaultdict. Usin
3 min read
Remove common elements from two list in Python
When working with two lists in Python, we may need to remove the common elements between them. A practical example could be clearing out overlapping tasks between two to-do lists. The most efficient way to remove common elements between two lists is by using sets. [GFGTABS] Python a = [1, 2, 3, 4, 5
3 min read
Python | Find most frequent element in a list
Given a list, find the most frequent element in it. If multiple elements appear a maximum number of times, print any one of them using Python. Example Make a set of the list so that the duplicate elements are deleted. Then find the highest count of occurrences of each element in the set and thus, we
2 min read
Python - Elements frequency count in multiple lists
Sometimes while working with Python lists we can have a problem in which we need to extract the frequency of elements in list. But this can be added work if we have more than 1 list we work on. Let's discuss certain ways in which this task can be performed. Method #1: Using dictionary comprehension
6 min read
Python | Print the common elements in all sublists
Given a list of lists, the task is to find the elements which are common in all sublist. There are various approaches to do this task. Let's discuss the approaches one by one. Method #1: Using set C/C++ Code # Python code to find duplicate element in all # sublist from list of list # List of list in
3 min read
Python program to find common elements in three lists using sets
We are given three lists we need to find common elements in all three lists using sets. For example a = [1, 2, 3, 4], b = [2, 3, 5, 6] and c = [1, 2, 3, 7]. We need to find all common elements so that resultant output should be {2, 3}. Using set.intersection()set.intersection() method finds common e
3 min read
Python Program to Find Most common elements set
Given a List of sets, the task is to write a Python program tocompare elements with argument set, and return one with maximum matching elements. Examples: Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}], arg_set = {9, 6, 5, 3}Output : {9, 3, 5, 7}Explanation : Resultant
5 min read
Convert List of Lists to Dictionary - Python
We are given list of lists we need to convert it to python . For example we are given a list of lists a = [["a", 1], ["b", 2], ["c", 3]] we need to convert the list in dictionary so that the output becomes {'a': 1, 'b': 2, 'c': 3}. Using Dictionary ComprehensionUsing dictionary comprehension, we ite
3 min read
Python - Duplicate Element Indices in List
We are having a list we need to find the duplicate element indices. For example, we are given a list a = [10, 20, 30, 20, 40, 30, 50] we need to find indices of the duplicate items so that output should be {20: [1, 3], 30: [2, 5]}. Using a loop and a dictionaryWe iterate through the list using enume
3 min read