Print All Sublists of a List in Python
Last Updated :
08 Feb, 2025
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]]
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.
Python
from itertools import combinations
a = [1, 2, 3]
res = [list(combinations(a, r)) for r in range(1, len(a) + 1)]
res = [list(sublist) for g in res for sublist in g]
print(res)
Output[[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
Explanation:
- function combinations(a, r) picks r elements from a while maintaining order ensuring only continuous selections are made.
- list comprehension [list(combinations(a, r)) for r in range(1, len(a) + 1)] gathers sublists of all possible lengths.
- second list comprehension [list(sublist) for group in result for sublist in group] extracts each combination from nested lists and converts them into a flat structure.
Let's explore some other methods and see how we can print all sublists of a list in Python
Using List Comprehension
List comprehension allows us to generate all continuous sublists in a single line making the code more compact and readable.
Python
a = [1, 2, 3]
res = [a[i:j] for i in range(len(a)) for j in range(i + 1, len(a) + 1)]
print(res)
Output[[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
Explanation:
- We iterate through all possible start (i) and end (j) indices and expression a[i:j] extracts a sublist from index i to j.
- Instead of using multiple loops everything is combined in a single line.
Using Recursion
Recursion helps generate all sublists by breaking the problem into smaller parts, making the approach more structured and logical.
Python
def sublists(a, start=0):
if start == len(a):
return [[]]
s_sublists = sublists(a, start + 1)
return [[a[start]] + sub for sub in s_sublists] + s_sublists
a = [1, 2, 3]
res = sublists(a)
print(res)
Output[[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]
Explanation:
- sublists function generates all subsets of a list using recursion.
- It starts with a base case returning [[]] for an empty list and recursively combines subsets of smaller lists with new subsets including the first element.
Using Nested Loops
We use two nested loops to generate all possible continuous sublists by slicing the list.
Python
a = [1, 2, 3]
res = []
for i in range(len(a)):
for j in range(i + 1, len(a) + 1):
res.append(a[i:j])
print(res)
Output[[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
Explanation:
- outer loop (i) starts at each element and the inner loop (j) extends the sublist from i to j.
- a[i:j] extracts the continuous sublist and each sublist is stored in result.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice