Python | Print the common elements in all sublists
Last Updated :
20 Apr, 2023
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
Python3
Input = [ [ 10 , 20 , 30 , 40 ],
[ 30 , 40 , 60 , 70 ],
[ 20 , 30 , 40 , 60 , 70 ],
[ 30 , 40 , 80 , 90 ], ]
Output = set ( Input [ 0 ])
for l in Input [ 1 :]:
Output & = set (l)
Output = list (Output)
print (Output)
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2: Using reduce and map
Python3
import operator
from functools import reduce
Input = [ [ 10 , 20 , 30 , 40 ],
[ 30 , 40 , 60 , 70 ],
[ 20 , 30 , 40 , 60 , 70 ],
[ 30 , 40 , 80 , 90 ], ]
out = reduce (operator.iand, map ( set , Input ))
out = list (out)
print (out)
|
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the output list.
Method #3: Using set.intersection
Python3
from functools import reduce
def func(a, b):
return list ( set (a).intersection( set (b)))
Input = [ [ 10 , 20 , 30 , 40 ],
[ 30 , 40 , 60 , 70 ],
[ 20 , 30 , 40 , 60 , 70 ],
[ 30 , 40 , 80 , 90 ], ]
out = reduce (func, Input )
print (out)
|
Method #3: Using all()
Another approach to find common elements in all sublists could be using the built-in all function and a list comprehension. Here’s an example of how this could work:
Python3
Input = [ [ 10 , 20 , 30 , 40 ],
[ 30 , 40 , 60 , 70 ],
[ 20 , 30 , 40 , 60 , 70 ],
[ 30 , 40 , 80 , 90 ], ]
common_elements = [x for x in Input [ 0 ] if all (x in sublist for sublist in Input )]
print (common_elements)
|
This will iterate through each element in the first sublist, and check if that element is present in all of the other sublists. If it is, it will be added to the common_elements list. At the end, the common_elements list will contain the elements that are common to all sublists.
Share your thoughts in the comments
Please Login to comment...