Related Articles

Related Articles

Python | Remove unidentical lists
  • Last Updated : 14 Jan, 2020

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]]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :