Python | Remove sublists that are present in another sublist

Given a list of lists, write a Python program to remove sublists from the given list of lists that are present in another sublist.

Examples:

Input : [['a', 'b', 'c'], ['a', 'c'], ['a', 'b', 'c'], ['d']]
Output : [['a', 'b', 'c'], ['d']]

Input : [[1], [1, 2], [1, 2, 3], [0], [0, 1]]
Output : [[1, 2, 3], [0, 1]]

 
Approach #1 : Using Python Set (If order of list doesn’t matter)



This approach makes use of Python sets. Create two empty lists ‘curr_res’ to store current sublist and ‘result’ to store the finalized sublists. Convert the sub-lists in the given list of lists to sets and sort them by length in reverse order, so that you can iterate through them and add each set to the curr_res only if it is not a subset of any of the existing sets in the curr_res.
The only drawback of this approach is that it may produce the result in an unordered way(Since sets are unordered).

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to remove sublists from
# list of lists that are in another sublist
  
def removeSublist(lst):
    curr_res = []
    result = []
    for ele in sorted(map(set, lst), key = len, reverse = True):
        if not any(ele <= req for req in curr_res):
            curr_res.append(ele)
            result.append(list(ele))
          
    return result
      
# Driver code
lst = [['a', 'b', 'c'], ['a', 'b'], ['a', 'b', 'c'], ['d']]
print(removeSublist(lst))

chevron_right


Output:

[['c', 'b', 'a'], ['d']]

 
Approach #2 : Using Python Dictionary (If order of list matters)

Dict may not always produce ordered output, therefore you can use OrderedDict from collections module.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to remove sublists from
# list of lists that are in another sublist
from collections import OrderedDict
  
def removeSublist(lst):
    curr_result = []
    result = []
    for ele in sorted(map(OrderedDict.fromkeys, lst), key = len, reverse = True):
        if not any(ele.keys() <= req.keys() for req in curr_result):
            curr_result.append(ele)
            result.append(list(ele))
              
    return result
      
# Driver code
lst = [['a', 'b', 'c'], ['a', 'b'], ['a', 'b', 'c'], ['d']]
print(removeSublist(lst))

chevron_right


Output:

[['a', 'b', 'c'], ['d']]


My Personal Notes arrow_drop_up


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.