Open In App

Python program to find common elements in three lists using sets

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

Prerequisite: Sets in Python Given three arrays, we have to find common elements in three sorted lists using sets. Examples :

Input : ar1 = [1, 5, 10, 20, 40, 80]
        ar2 = [6, 7, 20, 80, 100]
        ar3 = [3, 4, 15, 20, 30, 70, 80, 120]

Output : [80, 20]

Input : ar1 = [1, 5, 5]
        ar2 = [3, 4, 5, 5, 10]
        ar3 = [5, 5, 10, 20]

Output : [5]

Method 1: We have given three arrays, with the help of sets one can easily find out the intersection of these Arrays. Intersection method simply provides the intersection of both the arrays upon which you want to perform the operation of intersection (or, it simply gives out the common elements in both the array). We will be taking three arrays and then we will take out the intersection. Below is the implementation of above approach : 

Python3




# Python3 program to find common elements
# in three lists using sets
 
def IntersecOfSets(arr1, arr2, arr3):
    # Converting the arrays into sets
    s1 = set(arr1)
    s2 = set(arr2)
    s3 = set(arr3)
     
    # Calculates intersection of
    # sets on s1 and s2
    set1 = s1.intersection(s2)         #[80, 20, 100]
     
    # Calculates intersection of sets
    # on set1 and s3
    result_set = set1.intersection(s3)
     
    # Converts resulting set to list
    final_list = list(result_set)
    print(final_list)
 
# Driver Code
if __name__ == '__main__' :
     
    # Elements in Array1
    arr1 = [1, 5, 10, 20, 40, 80, 100]
     
    # Elements in Array2
    arr2 = [6, 7, 20, 80, 100]
     
    # Elements in Array3
    arr3 = [3, 4, 15, 20, 30, 70, 80, 120]
     
    # Calling Function
    IntersecOfSets(arr1, arr2, arr3)


Output

[80, 20]

Time complexity: O(n), where n is the size of the largest input array.
Auxiliary space: O(m), where m is the size of the resulting set.

Method 2: Using Set

One alternative approach using sets is to iterate over the elements in one of the lists and check if they are present in the other two lists using the in operator. If an element is present in all three lists, it can be added to a new set or list to store the common elements.

For example:

Python3




def find_common(list1, list2, list3):
    common = set()
    for elem in list1:
        if elem in list2 and elem in list3:
            common.add(elem)
    return common
 
list1 = [1, 5, 10, 20, 40, 80]
list2 = [6, 7, 20, 80, 100]
list3 = [3, 4, 15, 20, 30, 70, 80, 120]
 
common = find_common(list1, list2, list3)
print(common)


Output

{80, 20}

Time complexity: O(n), where n is the size of list1.
Auxiliary space: O(m), where m is the size of the set of common elements

Method 3: Here is another approach using list comprehension and the intersection method of sets:

Python3




def find_common(list1, list2, list3):
    # Convert lists to sets
    set1 = set(list1)
    set2 = set(list2)
    set3 = set(list3)
     
    # Use list comprehension to find common elements
    # in all three sets and return as a list
    return [elem for elem in set1 if elem in set2 and elem in set3]
 
list1 = [1, 5, 10, 20, 40, 80]
list2 = [6, 7, 20, 80, 100]
list3 = [3, 4, 15, 20, 30, 70, 80, 120]
 
common = find_common(list1, list2, list3)
print(common)


Output

[80, 20]

Time complexity: O(n), where n is the total number of elements in the three lists.
Auxiliary space: O(n)

Method 4: Use a loop to iterate over the elements of one list and check if they exist in the other two lists. Here’s an example:

Python3




def IntersecOfSets(arr1, arr2, arr3):
    result = []
    for i in arr1:
        if i in arr2 and i in arr3:
            result.append(i)
    print(list(set(result)))
     
arr1 = [1, 5, 10, 20, 40, 80]
arr2 = [6, 7, 20, 80, 100]
arr3 = [3, 4, 15, 20, 30, 70, 80, 120]
 
common = IntersecOfSets(arr1, arr2, arr3)


Output

[20, 80]

Time complexity: O(n^2), where n is the length of the largest input list.
Auxiliary space: O(m), where m is the size of the resulting list.

Method 5: Using the built-in function filter() and lambda function to find the intersection of the arrays.

  • Define a lambda function that takes an element as an argument and checks if it is present in all three arrays.
  • Use the filter() function to apply the lambda function to each element of the first array and return only those elements that satisfy the condition.
  • Convert the filtered result into a list and return it as the intersection of the three arrays.

Python3




def IntersecOfSets(arr1, arr2, arr3):
    common = list(filter(lambda x: x in arr2 and x in arr3, arr1))
    print(common)
 
arr1 = [1, 5, 10, 20, 40, 80]
arr2 = [6, 7, 20, 80, 100]
arr3 = [3, 4, 15, 20, 30, 70, 80, 120]
 
IntersecOfSets(arr1, arr2, arr3)


Output

[20, 80]

Time complexity: O(n) where n is the length of the first array (assuming constant time set lookup and set intersection operations).
Auxiliary space: O(m) where m is the number of elements that are common in all three arrays (assuming worst-case scenario where all elements are common).



Similar Reads

Python Program to Find Duplicate sets in list of sets
Given a list of sets, the task is to write a Python program to find duplicate sets. Input : test_list = [{4, 5, 6, 1}, {6, 4, 1, 5}, {1, 3, 4, 3}, {1, 4, 3}, {7, 8, 9}]Output : [frozenset({1, 4, 5, 6}), frozenset({1, 3, 4})]Explanation : {1, 4, 5, 6} is similar to {6, 4, 1, 5} hence part of result. Input : test_list = [{4, 5, 6, 9}, {6, 4, 1, 5}, {
8 min read
Python Program for Find a triplet from three linked lists with sum equal to a given number
Given three linked lists, say a, b and c, find one node from each list such that the sum of the values of the nodes is equal to a given number. For example, if the three linked lists are 12->6->29, 23->5->8, and 90->20->59, and the given number is 101, the output should be triple "6 5 90".In the following solutions, size of all th
4 min read
Python | Find common elements in list of lists
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 + s
6 min read
Python program to check if the list contains three consecutive common numbers in Python
Our task is to print the element which occurs 3 consecutive times in a Python list. Example : Input : [4, 5, 5, 5, 3, 8] Output : 5 Input : [1, 1, 1, 64, 23, 64, 22, 22, 22] Output : 1, 22 Approach : Create a list.Create a loop for range size – 2.Check if the element is equal to the next element.Again check if the next element is equal to the next
3 min read
Find common elements in three sorted arrays by dictionary intersection
One way to efficiently find shared items in three sorted arrays is by using dictionary intersection. However, it's important to note that dictionaries are commonly used for unique keys, so if there are duplicate elements in your arrays, some adjustments may be needed to make this approach work. Given three arrays sorted in non-decreasing order, pri
4 min read
Python - Convert List of lists to list of Sets
Given a list containing lists, the task is to write a Python Program to convert it to a list containing sets. Examples: Input : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]Output : [{1, 2}, {1, 2, 3}, {2}, {0}]Input : [[4, 4], [5, 5, 5], [1, 2, 3]]Output : [{4}, {5}, {1, 2, 3}]Python Convert List of lists to list of SetsBelow are the ways by which we
4 min read
Python Convert Dict of Lists to Dict of Sets
In Python, converting a dictionary of lists to a dictionary of sets is a valuable process for optimizing data structures. This transformation enhances efficiency by eliminating duplicates and enabling efficient membership testing. Utilizing built-in functions like set() and list comprehension simplifies the conversion process. Example : Input: dict
3 min read
Create three lists of numbers, their squares and cubes using Python
In this article, we are going to create a list of the numbers in a particular range provided in the input, and the other two lists will contain the square and the cube of the list in the given range using Python. Input: Start = 1, End = 10Output:Numbers_list = [1,2,3,4,5,6,7,8,9,10]Squares_list= [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]Cubes_list = [1
4 min read
Python | Print all the common elements of two lists
Given two lists, print all the common elements of two lists. Examples: Input : list1 = [1, 2, 3, 4, 5] list2 = [5, 6, 7, 8, 9] Output : {5} Explanation: The common element of the lists is 5. Input : list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9] Output : No common elements Explanation: They do not have any elements in common in between them Method 1:
8 min read
Python | Merge List with common elements in a List of Lists
Given a list of list, we have to merge all sub-list having common elements. These type of problems are very frequent in College examinations and while solving coding competitions. Below are some ways to achieve this. Input: [[11, 27, 13], [11, 27, 55], [22, 0, 43], [22, 0, 96], [13, 27, 11], [13, 27, 55], [43, 0, 22], [43, 0, 96], [55, 27, 11]] Out
3 min read