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Â
Python3
# Python code to find duplicate element in all # sublist from list of listÂ
# List of list initializationInput = [ [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)Â
# Converting to listOutput = list(Output)Â
# Printing answerprint(Output) |
[40, 30]
Time Complexity: O(n)
Auxiliary Space: O(1)
 Method #2: Using reduce and mapÂ
Python3
# Python code to find duplicate element in all # sublist from list of listimport operatorfrom functools import reduceÂ
# List of list initializationInput = [ [10, 20, 30, 40],          [30, 40, 60, 70],          [20, 30, 40, 60, 70],           [30, 40, 80, 90], ]Â
# using reduce and mapout = reduce(operator.iand, map(set, Input))Â
# Converting into listout = list(out)Â
# Printing outputprint(out) |
[40, 30]
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
# Python code to find duplicate element in all # sublist from list of listÂ
# importing reduce from functools import reduceÂ
# function for set intersectiondef func(a, b):Â Â Â Â return list(set(a).intersection(set(b)))Â
# List of list initializationInput = [ [10, 20, 30, 40],          [30, 40, 60, 70],          [20, 30, 40, 60, 70],           [30, 40, 80, 90], ]Â
# using reduce and set.intersectionout = reduce(func, Input)Â
# Printing outputprint(out) |
[40, 30]
 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
# Python code to find duplicate element in all # sublist from list of listInput = [ [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 code is contributed by Edula Vinay Kumar Reddy |
[30, 40]
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.



