Advertisement
makispaiktis

Generate all the sublists of a given list

Aug 21st, 2020 (edited)
353
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.89 KB | None | 0 0
  1. from itertools import combinations
  2.  
  3. # Function 1 <----> Generate all the sublists of a list
  4. # If list = [1, 2, 3], there are 8 sublists:
  5. # [], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]
  6.  
  7. def subLists(myList):
  8.     N = len(myList)
  9.     returnedList = list()
  10.     returnedList.append([])
  11.     for remaining in range(1, N):
  12.         combinationsOfIndecesRemaining = list(combinations(list(range(N)), remaining))
  13.         for comb in combinationsOfIndecesRemaining:
  14.             sublist = list()
  15.             for i in range(len(comb)):
  16.                 sublist.append(myList[comb[i]])
  17.             returnedList.append(sublist)
  18.     returnedList.append(myList)
  19.     return returnedList
  20.  
  21. # MAIN FUNCTION
  22. print()
  23. l = [0, 1, 2, 3, 4]
  24. sub = subLists(l)
  25. print("List = " + str(l))
  26. print("Sublists = " + str(sub))
  27. print("There are " + str(len(sub)) + " = 2^" + str(len(l)) + " sublists of the list " + str(l))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement