Python | Triple list difference
Last Updated :
21 Apr, 2023
The difference between 2 lists have been dealt previously, but sometimes, we can have more than two lists and we need to find the mutual differences of one list with every other list. This kind of problem has applications in many domains. Let's discuss certain ways in which this problem can be solved.
Method #1 : Using map() + set() + list comprehension The combination of above 3 functions can be used to perform this particular task. The map function can be used to convert the list to set by the set function and list comprehension can be used to get the new mutual difference list for each list.
Python3
# Python3 code to demonstrate
# triple list difference
# using map() + set() + list comprehension
# initializing lists
test_list1 = [1, 5, 6, 4, 7]
test_list2 = [8, 4, 3]
test_list3 = [9, 10, 3, 5]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
print("The original list 3 : " + str(test_list3))
# using map() + set() + list comprehension
# triple list difference
temp1, temp2, temp3 = map(set, (test_list1, test_list2, test_list3))
res1 = [ele for ele in test_list1 if ele not in temp2 and ele not in temp3]
res2 = [ele for ele in test_list2 if ele not in temp1 and ele not in temp3]
res3 = [ele for ele in test_list3 if ele not in temp2 and ele not in temp1]
# print result
print("The mutual difference list are : "
+ str(res1) + " " + str(res2) + " " + str(res3))
Output : The original list 1 : [1, 5, 6, 4, 7]
The original list 2 : [8, 4, 3]
The original list 3 : [9, 10, 3, 5]
The mutual difference list are : [1, 6, 7] [8] [9, 10]
Method #2 : Using map() + set() + "-" operator This problem can also be solved the minus operator, if one wishes not to use the list comprehension. The minus operator can perform the boolean match difference to compute the valid set difference.
Python3
# Python3 code to demonstrate
# triple list difference
# using map() + set() + "-" operator
# initializing lists
test_list1 = [1, 5, 6, 4, 7]
test_list2 = [8, 4, 3]
test_list3 = [9, 10, 3, 5]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
print("The original list 3 : " + str(test_list3))
# using map() + set() + "-" operator
# triple list difference
temp1, temp2, temp3 = map(set, (test_list1, test_list2, test_list3))
res1 = temp1 - temp2 - temp3
res2 = temp2 - temp3 - temp1
res3 = temp3 - temp1 - temp2
res1, res2, res3 = map(list, (res1, res2, res3))
# print result
print("The mutual difference list are : "
+ str(res1) + " " + str(res2) + " " + str(res3))
Output : The original list 1 : [1, 5, 6, 4, 7]
The original list 2 : [8, 4, 3]
The original list 3 : [9, 10, 3, 5]
The mutual difference list are : [1, 6, 7] [8] [9, 10]
Method #3 :Using the lambda, set(), filter() function: This approach involves using the filter() function to remove elements that are present in one of the other lists. It can be implemented as follows:
Python3
def mutual_difference(list1, list2, list3):
# Use filter() to remove elements that are present in one of the other lists
result1 = list(filter(lambda x: x not in set(list2) and x not in set(list3), set(list1)))
result2 = list(filter(lambda x: x not in set(list1) and x not in set(list3), set(list2)))
result3 = list(filter(lambda x: x not in set(list1) and x not in set(list2), set(list3)))
return result1, result2, result3
# Initialize lists
test_list1 = [1, 5, 6, 4, 7]
test_list2 = [8, 4, 3]
test_list3 = [9, 10, 3, 5]
# Print original lists
print("The original list 1 :", test_list1)
print("The original list 2 :", test_list2)
print("The original list 3 :", test_list3)
# Get mutual difference lists
mutual_difference_lists = mutual_difference(test_list1, test_list2, test_list3)
# Print result
print("The mutual difference list are :", mutual_difference_lists)
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list 1 : [1, 5, 6, 4, 7]
The original list 2 : [8, 4, 3]
The original list 3 : [9, 10, 3, 5]
The mutual difference list are : ([1, 6, 7], [8], [9, 10])
The time complexity of the mutual_difference() function using the filter() function is O(n), where n is the total number of elements in all three lists. This is because the filter() function processes each element in the lists once.
The auxiliary space is also O(n), because the result lists are stored in memory and will have a size of O(n).
Method#4; Using Iteration
Approach
this approach uses iteration to find the difference between the lists. It involves iterating over each element in the lists and checking if it is present in the other two lists. If the element is not present in any of the other two lists, it is added to the mutual difference list.
Algorithm
1. Initialize the original lists.
2. Create empty lists for the mutual difference for each of the original lists.
3. For each element in the first list, check if it is not present in the second and third lists. If it is not present, add it to the mutual difference list for the first list.
4. For each element in the second list, check if it is not present in the first and third lists. If it is not present, add it to the mutual difference list for the second list.
5. For each element in the third list, check if it is not present in the first and second lists. If it is not present, add it to the mutual difference list for the third list.
6. Print the mutual difference lists.
Python3
list1 = [1, 5, 6, 4, 7]
list2 = [8, 4, 3]
list3 = [9, 10, 3, 5]
# Print original lists
print("The original list 1 :", list1)
print("The original list 2 :", list2)
print("The original list 3 :", list3)
diff1 = []
for x in list1:
if x not in list2 and x not in list3:
diff1.append(x)
diff2 = []
for x in list2:
if x not in list1 and x not in list3:
diff2.append(x)
diff3 = []
for x in list3:
if x not in list1 and x not in list2:
diff3.append(x)
print("Mutual difference list: ", (diff1, diff2, diff3))
OutputThe original list 1 : [1, 5, 6, 4, 7]
The original list 2 : [8, 4, 3]
The original list 3 : [9, 10, 3, 5]
Mutual difference list: ([1, 6, 7], [8], [9, 10])
Time complexity: O(n^2), where n is the length of the longest list. This is because for each element in the list, we are iterating over the other two lists, resulting in a nested loop.
Space complexity: O(n), where n is the length of the longest list. This is because we are storing the mutual difference lists in separate variables, which can grow up to the size of the longest list.
METHOD 5:Using itertools
APPROACH:
In this Approach we combine the three lists into a single iterable using the itertools.chain() function. Then, we use the collections.Counter() function to count the occurrences of each element in the iterable. Finally, we use list comprehension to filter out the elements that have a count of 1, which means they occur in only one list.
ALGORITHM:
1.Import the itertools and collections modules.
2.Define the three input lists list1, list2, and list3.
3.Use the itertools.chain() function to combine the three lists into a single iterable merged_list.
4.Use the collections.Counter() function to count the occurrences of each element in merged_list and store the result in a counter dictionary.
5.Use list comprehension to filter out the elements that have a count of 1 from each input list:
6.For diff1, filter out the elements in list1 that have a count of 1 in the counter dictionary.
7.For diff2, filter out the elements in list2 that have a count of 1 in the counter dictionary.
8.For diff3, filter out the elements in list3 that have a count of 1 in the counter dictionary.
9.Print the resulting lists diff1, diff2, and diff3
Python3
import itertools
import collections
list1 = [1, 5, 6, 4, 7]
list2 = [8, 4, 3]
list3 = [9, 10, 3, 5]
merged_list = itertools.chain(list1, list2, list3)
counter = collections.Counter(merged_list)
diff1 = [element for element in list1 if counter[element] == 1]
diff2 = [element for element in list2 if counter[element] == 1]
diff3 = [element for element in list3 if counter[element] == 1]
print(diff1, diff2, diff3)
Output[1, 6, 7] [8] [9, 10]
The time complexity is O(n) and the auxiliary space is also O(n), where n is the total number of elements in all three input lists.
METHOD 6:Using numpy:
Algorithm:
- Concatenate the given lists using NumPy's concatenate function.
- Use NumPy's unique and return_counts functions to get the count of each element in the merged list.
- Convert the unique and counts NumPy arrays into a Python dictionary using the dict function.
- Use the filter function to filter the elements in each list with a count of 1.
- Return the filtered lists.
Python3
import numpy as np
import heapq
list1 = [1, 5, 6, 4, 7]
list2 = [8, 4, 3]
list3 = [9, 10, 3, 5]
# Print original lists
print("The original list 1 :", list1)
print("The original list 2 :", list2)
print("The original list 3 :", list3)
merged_list = np.concatenate((list1, list2, list3))
unique, counts = np.unique(merged_list, return_counts=True)
counter = dict(zip(unique, counts))
diff1 = list(filter(lambda x: counter[x] == 1, list1))
diff2 = list(filter(lambda x: counter[x] == 1, list2))
diff3 = list(filter(lambda x: counter[x] == 1, list3))
print(diff1, diff2, diff3)
#This code is contributed by Jyothi pinjala.
Output:
The original list 1 : [1, 5, 6, 4, 7]
The original list 2 : [8, 4, 3]
The original list 3 : [9, 10, 3, 5]
[1, 6, 7] [8] [9, 10]
Time complexity:
The time complexity of this algorithm depends on the implementation of the NumPy functions used. The concatenate function takes O(n) time where n is the total number of elements in the merged list. The unique and return_counts functions take O(n log n) time, where n is the total number of elements in the merged list. The filter function takes O(n) time where n is the length of the list. Therefore, the overall time complexity of the algorithm is O(n log n).
Space complexity:
The space complexity of this algorithm depends on the size of the merged list and the number of unique elements in the merged list. The concatenate function creates a new NumPy array with a size equal to the total number of elements in the merged list. The unique and return_counts functions create two NumPy arrays with a size equal to the number of unique elements in the merged list. The dict function creates a dictionary with a size equal to the number of unique elements in the merged list. The filter function creates a new list with a size equal to the number of filtered elements. Therefore, the overall space complexity of the algorithm is O(n).
Similar Reads
Python | Difference in Record Lists
Sometimes, while working with data, we may have a problem in which we require to find the difference records between two lists that we receive. This is a very common problem and records usually occurs as a tuple. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using list
5 min read
Python | Triplet iteration in List
List iteration is common in programming, but sometimes one requires to print the elements in consecutive triplets. This particular problem is quite common and having a solution to it always turns out to be handy. Lets discuss certain way in which this problem can be solved. Method #1 : Using list co
6 min read
Difference between two Lists in Python
The difference between two lists in Python refers to the elements that are present in one list but not in the other. For example, finding the difference between lists a = [1, 2, 3, 4] and b = [3, 4, 5, 6] can result in [1, 2] by removing the common elements (3 and 4).Using setSet operations are most
3 min read
Python - Element wise Matrix Difference
Given two Matrixes, the task is to write a Python program to perform element-wise difference. Examples: Input : test_list1 = [[2, 4, 5], [5, 4, 2], [1, 2, 3]], test_list2 = [[6, 4, 6], [9, 6, 3], [7, 5, 4]] Output : [[4, 0, 1], [4, 2, 1], [6, 3, 1]] Explanation : 6 - 2 = 4, 4 - 4 = 0, 6 - 5 = 1. And
3 min read
Difference between List VS Set VS Tuple in Python
In Python, Lists, Sets and Tuples store collections but differ in behavior. Lists are ordered, mutable and allow duplicates, suitable for dynamic data. Sets are unordered, mutable and unique, while Tuples are ordered, immutable and allow duplicates, ideal for fixed data. List in PythonA List is a co
2 min read
Python - Consecutive Tuple difference
Given List of tuples, find index-wise absolute difference of consecutive tuples. Input : test_list = [(5, 3), (1, 4), (9, 5), (3, 5)] Output : [(4, 1), (7, 1), (6, 0)] Explanation : 5 - 1 = 4, 4 - 3 = 1. hence (4, 1) and so on. Input : test_list = [(9, 5), (3, 5)] Output : [(6, 0)] Explanation : 9 -
4 min read
Python - Get minimum difference in Tuple pair
Sometimes, while working with data, we might have a problem in which we need to find minimum difference between available pairs in list. This can be application to many problems in mathematics domain. Letâs discuss certain ways in which this task can be performed.Method #1 : Using min() + list compr
4 min read
List of strings in Python
A list of strings in Python stores multiple strings together. In this article, weâll explore how to create, modify and work with lists of strings using simple examples.Creating a List of StringsWe can use square brackets [] and separate each string with a comma to create a list of strings.Pythona =
2 min read
Python - Maximum difference across lists
Given two lists, the task is to write a Python program to find maximum difference among like index elements. Examples: Input : test_list1 = [3, 4, 2, 1, 7], test_list2 = [6, 2, 1, 9, 1]Output : 8Explanation : 9 - 1 = 8 is maximum difference across lists in same index. Input : test_list1 = [3, 4, 2,
4 min read
Sort Tuple of Lists in Python
The task of sorting a tuple of lists involves iterating through each list inside the tuple and sorting its elements. Since tuples are immutable, we cannot modify them directly, so we must create a new tuple containing the sorted lists. For example, given a tuple of lists a = ([2, 1, 5], [1, 5, 7], [
3 min read