Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python | Remove repeated sublists from given list

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given a list of lists, write a Python program to remove all the repeated sublists (also with different order) from given list. Examples:

Input : [[1], [1, 2], [3, 4, 5], [2, 1]]
Output : [[1], [1, 2], [3, 4, 5]]

Input : [['a'], ['x', 'y', 'z'],  ['m', 'n'], ['a'], ['m', 'n']]
Output : [['a'], ['x', 'y', 'z'], ['m', 'n']]

  Approach #1 : Set comprehension + Unpacking Our first approach is to use set comprehension with sorted tuple. In every iteration in the list, we convert the current sublist to a sorted tuple, and return a set of all these tuples, which in turn eliminates all repeated occurrences of the sublists and thus, remove all repeated rearranged sublists. 

Python3




# Python3 program to Remove repeated
# unordered sublists from list
 
def Remove(lst):
     return ([list(i) for i in {*[tuple(sorted(i)) for i in lst]}]) 
      
# Driver code
lst = [[1], [1, 2], [3, 4, 5], [2, 1]]
print(Remove(lst))

Output:

[[1, 2], [3, 4, 5], [1]]

Time Complexity: O(n), where n is the number of elements in the list
Auxiliary Space: O(n), where n is the number of elements in the list 

  Approach #2 : Using map() with set and sorted tuples. 

Python3




# Python3 program to Remove repeated
# unordered sublists from list
 
def Remove(lst):
     return list(map(list, (set(map(lambda x: tuple(sorted(x)), lst)))))
      
# Driver code
lst = [[1], [1, 2], [3, 4, 5], [2, 1]]
print(Remove(lst))

Output:

[[1, 2], [3, 4, 5], [1]]

Time Complexity: O(n) where n is the number of elements in the list 
Auxiliary Space: O(1), extra space is not required 

With maintaining order – Approach #3 : Using sorted tuple as hash First, we initialize an empty list as ‘res’ and a set as ‘check’. Now, For each sublist in the list, convert the sublist to sorted tuple and save it in ‘hsh’. Then check if hsh is present in check or not. If not, append the current sublist to ‘.res’ and ‘hsh’ to ‘check’. This way it would be easier to maintain the order to sublists. 

Python3




# Python3 program to Remove repeated
# unordered sublists from list
 
def Remove(lst):
     res = []
     check = set()
 
     for x in lst:
         hsh = tuple(sorted(x))
         if hsh not in check:
             res.append(x)
             check.add(hsh)
              
     return res
      
# Driver code
lst = [[1], [1, 2], [3, 4, 5], [2, 1]]
print(Remove(lst))

Output:

[[1], [1, 2], [3, 4, 5]]

Time Complexity: O(nlogn)
Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Last Updated : 17 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials