Python | Remove unidentical lists
Last Updated :
01 May, 2023
Sometimes, while working with Python lists, we can have a binary matrix ( Nested list having 2 elements ). And we can have a problem in which we need to remove unidentical lists. A pair is unique irrespective of order, it doesn’t appear again in list. Let’s discuss certain way in which this task can be performed.
Method : Using frozenset() + Counter() + list comprehension
The combination of above functions can perform this task. The frozenset() is used for ignoring the ordering, Counter() is used to perform the task of checking the uniqueness and iteration is done using list comprehension.
Python3
from collections import Counter
test_list = [[ 5 , 6 ], [ 9 , 8 ], [ 8 , 9 ], [ 1 , 4 ], [ 6 , 5 ], [ 10 , 1 ]]
print ( "The original list is : " + str (test_list))
temp = Counter( frozenset (ele) for ele in test_list)
res = [ele for ele in test_list if temp[ frozenset (ele)] > = 2 ]
print ( "The list after removal of unidentical lists : " + str (res))
|
Output :
The original list is : [[5, 6], [9, 8], [8, 9], [1, 4], [6, 5], [10, 1]]
The list after removal of unidentical lists : [[5, 6], [9, 8], [8, 9], [6, 5]]
Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n*n), where n is the number of elements in the list “test_list”.
Method #2: Using loop:
Algorithm:
- Initialize an empty list res.
- Loop through each element in the test_list.
- For each element, loop through all the subsequent elements in the test_list.
- Check if the set of the current element is equal to the set of the subsequent element.
- If they are equal, add both elements to the res list and break out of the inner loop.
- Convert the list of tuples to a set to remove duplicates, and then convert it back to a list.
- Print the original list and the resulting list.
Python3
test_list = [[ 5 , 6 ], [ 9 , 8 ], [ 8 , 9 ], [ 1 , 4 ], [ 6 , 5 ], [ 10 , 1 ]]
print ( "The original list is : " + str (test_list))
res = []
for i in range ( len (test_list)):
for j in range (i + 1 , len (test_list)):
if set (test_list[i]) = = set (test_list[j]):
res.append(test_list[i])
res.append(test_list[j])
break
print ( "The list after removal of unidentical lists : " +
str ( list ( set ( map ( tuple , res)))))
|
Output
The original list is : [[5, 6], [9, 8], [8, 9], [1, 4], [6, 5], [10, 1]]
The list after removal of unidentical lists : [(5, 6), (9, 8), (8, 9), (6, 5)]
Time Complexity: O(n^2), where n is the length of the input list. This is because there are two nested loops that iterate through the entire list.
Auxiliary Space: O(n), where n is the length of the input list. This is because we are using a list res to store the matching elements, which can have a maximum size of n.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...