![]() |
VOOZH | about |
We are given a list and our task is to generate all possible sublists (continuous or non-continuous subsequences). For example: a = [1, 2, 3], the possible sublists are: [[], [1], [2], [3], [1, 2], [2, 3], [1, 3], [1, 2, 3]].
Let's explore some other methods and see how we can print all sublists of a list in Python
itertools.combinations() generates all possible subsets of a list in a highly optimized manner. The result is a list of all subsets including empty and full-length subsets.
[[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
Explanation:
List comprehension allows us to generate all continuous sublists in a single line making the code more compact and readable.
[[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
Explanation:
Note: This method only produces continuous sublists. Non-continuous sublists like [1, 3] are not included. Use itertools.combinations() or recursion for all possible sublists.
Recursion helps generate all sublists by breaking the problem into smaller parts, making the approach more structured and logical.
[[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]
Explanation:
We use two nested loops to generate all possible continuous sublists by slicing the list.
[[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
Explanation: