Get all possible sublists of a list in Python

In this tutorial, we shall be printing all sublists of a given list in Python. In this case, we shall be considering the same numbers also as different elements.

The user feeds the list but first, the program asks to enter the size of the list we will be entering. After the elements are fed to the program, it runs a nested loop and creates slices of the list and returns them as sublists.

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

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

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

Algorithm

  1. Enter the list and its length.
  2. Initialize a sublist that is empty initially.
  3. Use one for loop till the length of the given list.
  4. Run a nested loop to get all the sub-arrays from i to its right.
  5. Slice the subarray from i to j and append it to sublists.
  6. Print it.

Python program: Get all sublists of a list

# -*- coding: utf-8 -*-
"""
Created on Tue May  5 15:42:33 2020

@author: Vamsi Krishna
"""

def sublists(l): 

  # list to store all the sublists 
  sublist = [[]] 
  
  for i in range(len(l) + 1): 
 
    for j in range(i + 1, len(l) + 1): 
      
      sli = l[i:j]  # make a slice of the subarray 
      sublist.append(sli) #add it to the list of sublists
            
  return sublist 

l=list()
n=int(input("Enter the size of the List : "))
print("Enter the Elements of the List : ")
for i in range(int(n)):
   e=int(input())
   l.append(e)
print("Entered list is : {}".format(l))
print("Possible sublists are : ",sublists(l))
Output:
Enter the size of the List : 3
Enter the Elements of the List : 
1
3
5
Entered list is : [1, 3, 5]
Possible sublists are :  [[], [1], [1, 3], [1, 3, 5], [3], [3, 5], [5]]

Also Read: How to find all possible pairs with given sum in Python lists

Leave a Reply