Python | Remove unidentical lists

Sometimes, while working with python list, 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Remove unidentical lists
# using frozenset() + Counter() + list comprehension
from collections import Counter
  
# initialize list
test_list = [[5, 6], [9, 8], [8, 9], [1, 4], [6, 5], [10, 1]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Remove unidentical lists
# using frozenset() + Counter() + list comprehension
temp = Counter(frozenset(ele) for ele in test_list)
res = [ele for ele in test_list if temp[frozenset(ele)] >= 2]
  
# printing result
print("The list after removal of unidentical lists : " + str(res))

chevron_right


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]]
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.