Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Find Common elements in three Lists using Sets - Python
Next article icon

Python | Find common elements in list of lists

Last Updated : 13 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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




# Python3 code to demonstrate
# common element extraction form N lists
# using reduce() + lambda + set()
from functools import reduce
 
# initializing list of lists
test_list = [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# common element extraction form N lists
# using reduce() + lambda + set()
res = list(reduce(lambda i, j: i & j, (set(x) for x in test_list)))
 
# printing result
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




# Python3 code to demonstrate
# common element extraction form N lists
# using map() + intersection()
 
# initializing list of lists
test_list = [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# common element extraction form N lists
# using map() + intersection()
res = list(set.intersection(*map(set, test_list)))
 
# printing result
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




# Python3 code to find the common elements in a list of lists
 
# Initialize the list of lists
test_list = [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
 
# Print the original list
print("The original list is:", test_list)
 
# Find the common elements
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 result
print("The common elements are:", common_elements)
#This code is contributed by Edula Vinay Kumar Reddy
 
 
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




# Python3 code to demonstrate
# common element extraction form N lists
# using list comprehension and set intersection
 
# initializing list of lists
test_list = [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# common element extraction form N lists
# using list comprehension and set intersection
res = list(set(test_list[0]).intersection(*test_list[1:]))
 
# printing result
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. 



Next Article
Find Common elements in three Lists using Sets - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Find most common element in a 2D list
    Given a 2D list (may or may not be of same length), write a Python program to find the most common element in the given 2D list. Examples: Input : [[10, 20, 30], [20, 50, 10], [30, 50, 10]] Output : 10 Input : [['geeks', 'wins'], ['techie', 'wins']] Output : wins Approach #1 : Using max() function F
    5 min read
  • Python | Check if element exists in list of lists
    Given a list of lists, the task is to determine whether the given element exists in any sublist or not. Given below are a few methods to solve the given task. Method #1: Using any() any() method return true whenever a particular element is present in a given iterator. C/C++ Code # Python code to dem
    5 min read
  • 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 Common elements in three Lists using Sets - Python
    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
  • 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
  • Python - Combine list with other list elements
    Given two lists, combine list with each element of the other list. Examples: Input : test_list = [3, 5, 7], pair_list = ['Gfg', 'is', 'best'] Output : [([3, 5, 7], 'Gfg'), ([3, 5, 7], 'is'), ([3, 5, 7], 'best')] Explanation : All lists paired with each element from other list. Input : test_list = [3
    6 min read
  • Flatten a List of Lists in Python
    Flattening a list of lists means turning a nested list structure into a single flat list. This can be useful when we need to process or analyze the data in a simpler format. In this article, we will explore various approaches to Flatten a list of Lists in Python. Using itertools.chain itertools modu
    3 min read
  • Python - Check if two lists have at-least one element common
    Checking if two lists share at least one common element is a frequent task when working with datasets, filtering, or validating data. Python offers multiple efficient ways to solve this depending on the size and structure of the lists. Using set IntersectionConverting both lists into sets and findin
    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 - 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences