Open In App

Python | Print the common elements in all sublists

Last Updated : 20 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 initialization
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)
 
# Converting to list
Output = list(Output)
 
# Printing answer
print(Output)


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 list
import operator
from functools import reduce
 
# List of list initialization
Input = [ [10, 20, 30, 40],
          [30, 40, 60, 70],
          [20, 30, 40, 60, 70],
          [30, 40, 80, 90], ]
 
# using reduce and map
out = reduce(operator.iand, map(set, Input))
 
# Converting into list
out = list(out)
 
# Printing output
print(out)


Output:

[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 intersection
def func(a, b):
    return list(set(a).intersection(set(b)))
 
# List of list initialization
Input = [ [10, 20, 30, 40],
          [30, 40, 60, 70],
          [20, 30, 40, 60, 70],
          [30, 40, 80, 90], ]
 
# using reduce and set.intersection
out = reduce(func, Input)
 
# Printing output
print(out)


Output:

[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 list
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 code is contributed by Edula Vinay Kumar Reddy


Output

[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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads