# 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]]

```

### 3 responses to “Get all possible sublists of a list in Python”

1. ebrahim says:

It does not include [1,5] and generally, this algo does not support sublists of distance greater than 1 values in a list

2. VK says:

[1,5] is not a sublist of [1,3,5]. Only slices are considered to be sublists

3. vijay says:

it doesn’t include [1, 3] when we take [1, 2, 3, 4]