How to get all sublists of a list in Python

Get all sublists of a list in Python:

In this post, we will learn how to print all sublists from a list in Python. The input of the program is a list and output is a list holding all sublists. We will write one program that will take the list inputs one by one and print out the final output.

So, our program will work as like below:

  • Take the total size of the list from the user.
  • Read the values one by one from the user.
  • Print out the final list of sublists.

Algorithm to find sublists:

We will use one nested for loop to find out all combinations of a list.

  • Run one loop in range of 0 to length of the list.
  • Run one inner loop in range of current outer loop to length of the list.
  • Get the slice of the list in between the current indices pointed by the outer loop and inner loop.
  • Add the sliced list to the final list.
  • Return the final list.

Python program:

Below is the complete python program:

given_list = list()
result_list = list()

size = int(input('Enter the size of the list :'))

print('Enter all elements of the list :')

for i in range(size):
    given_list.append(int(input('Enter element to add : ')))

for i in range(len(given_list) + 1):
    for j in range(i + 1, len(given_list) + 1):
        result_list.append(given_list[i:j])

print(given_list)
print(result_list)

Here,

  • given_list is the original list entered by the user.
  • result_list is the final list i.e. lists of list.
  • size holds the size of the list. We are reading this value from the user.
  • The first for loop is used to read all values for the list one by one. We are using input to read the values and wrapping that in int() to convert to integer and appending the value to given_list.
  • The last nested for loops are used to make the final list result_list. It is a list of lists.
  • Finally, we are printing both original and final lists.

Output:

This program will print the below output:

Enter the size of the list :3
Enter all elements of the list :
Enter element to add : 1
Enter element to add : 2
Enter element to add : 3
[1, 2, 3]
[[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]


Enter the size of the list :5
Enter all elements of the list :
Enter element to add : 1
Enter element to add : 2
Enter element to add : 3
Enter element to add : 4
Enter element to add : 5
[1, 2, 3, 4, 5]
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2], [2, 3], [2, 3, 4], [2, 3, 4, 5], [3], [3, 4], [3, 4, 5], [4], [4, 5], [5]]

You might also like:

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊