28. Problem to generate all sublists with 5 or more elements.

In this program, we will take a user input as a list. Generate all sublists having 5 or more elements in it from the given list with the help of the below-given steps.

Generate all sublists of a list:

Steps to solve the program
  1. Take a list as input and create an empty list to store and generate all sublists.
  2. From itertools import combinations for generating sublists with 5 or more elements.
  3. Use for loop and range function for this purpose.
  4. If the generated list contains 5 or more elements add that list as a sublist to the empty list.
  5. Print the list to see the output.
				
					#Importing combinations
from itertools import combinations

#Input list
list1 = [1,3,5,8,0,22,45]

#Creating an empty list
sub = []

for i in range(0,len(list1)+1):
#Checking for combinations
    for sublist in combinations(list1,i):
        temp = list(sublist)
        if len(temp) > 4:
            sub.append(temp)

#Printing output
print(sub)
				
			

Output :

				
					[[1, 3, 5, 8, 0],
 [1, 3, 5, 8, 22],
 [1, 3, 5, 8, 45],
 [1, 3, 5, 0, 22],
 [1, 3, 5, 0, 45],
 [1, 3, 5, 22, 45],
 [1, 3, 8, 0, 22],
 [1, 3, 8, 0, 45],
 [1, 3, 8, 22, 45],
 [1, 3, 0, 22, 45],
 [1, 5, 8, 0, 22],
 [1, 5, 8, 0, 45],
 [1, 5, 8, 22, 45],
 [1, 5, 0, 22, 45],
 [1, 8, 0, 22, 45],
 [3, 5, 8, 0, 22],
 [3, 5, 8, 0, 45],
 [3, 5, 8, 22, 45],
 [3, 5, 0, 22, 45],
 [3, 8, 0, 22, 45],
 [5, 8, 0, 22, 45],
 [1, 3, 5, 8, 0, 22],
 [1, 3, 5, 8, 0, 45],
 [1, 3, 5, 8, 22, 45],
 [1, 3, 5, 0, 22, 45],
 [1, 3, 8, 0, 22, 45],
 [1, 5, 8, 0, 22, 45],
 [3, 5, 8, 0, 22, 45],
 [1, 3, 5, 8, 0, 22, 45]]
				
			

Related Articles

Check whether a list contains a sublist

Find the second largest number from the list

Leave a Comment