Given a list of lists, write a Python program to remove sublists from the given list of lists that are present in another sublist.
Input : [['a', 'b', 'c'], ['a', 'c'], ['a', 'b', 'c'], ['d']] Output : [['a', 'b', 'c'], ['d']] Input : [, [1, 2], [1, 2, 3], , [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).
[['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.
[['a', 'b', 'c'], ['d']]
- Python | Remove all sublists outside the given range
- Python | Remove repeated sublists from given list
- Python | Remove all values from a list present in other list
- Python | Adding value to sublists
- Python | Swapping sublists over given range
- Python | Merge elements of sublists
- Python | Add the occurrence of each number as sublists
- Python | Print all sublists of a list
- Python | Merge corresponding sublists from two different lists
- Python | Count unique sublists within list
- Python | Count the sublists containing given element in a list
- Python | Print the common elements in all sublists
- Python | Sort all sublists in given list of strings
- Python | Split a list into sublists of given lengths
- Python | Sort list of lists by the size of sublists
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.