Search code examples
pythonpython-3.xlistsublist

Split my list into n sub-lists and print all possibilities


I want to divide a list into n sub-lists and print all possible sub-lists. n is integer input by user. length of list can be anything 1<=n<=len(list)

For example 
if list = [1,2,3,4]
and n=1
solution = [1,2,3,4]
if n=2
solution=([1],[2,3,4]),([1,2],[3,4]),([1,2,3],[4])
if n=3
solution=([1],[2],[3,4]),([1,2],[3],[4]),([1],[2,3],[4])

Note:- brackets do not represent tuple or any other data type output can be in any form. Ps:-This is not a code but stackoverflow forced me to format it as such This is what I tried

''''python

lst=[]
lst1=[]
lst4=[]
for i in range(0,10000):
    element=int(input())
    lst.append(element)
    print("If you want to continue adding list press y else press n")
    choice=input()
    if choice=='y':
        continue
    elif choice=='n':
        break
    else:
        print("please enter a valid choice")
print("Enter division size")
N=int(input())
maxchunk=len(lst)-N+1
for j in range(maxchunk,0,-1):
    rchunk=(len(lst)-j)//(N-1)
    lst2=lst[0:j]
    lst1.append(lst2)
    chunksize=((len(lst)-j)+1)//(N-1)
    print(chunksize)
    for k in range(j,len(lst),chunksize):
        lst3=lst[k:k+chunksize]
        lst1.append(lst3)
    lst4.append(lst1)
    lst1=[]
print(lst4)

''''


Solution

  • You can use itertools.combinations to iterate over all the ways to choose n-1 split points of your list:

    from itertools import combinations
    
    lst = [10, 20, 30, 40, 50]
    n = 3
    
    result = []
    # n-1 split points:
    for indices in combinations(range(1, len(lst)), n-1):
        # indices are the indices of split points
        splits = []
        start = 0
        for stop in indices:
            splits.append(lst[start : stop])
            start = stop
        splits.append(lst[start : ])
        result.append(splits)
    

    result:

    [[[10], [20], [30, 40, 50]],
     [[10], [20, 30], [40, 50]],
     [[10], [20, 30, 40], [50]],
     [[10, 20], [30], [40, 50]],
     [[10, 20], [30, 40], [50]],
     [[10, 20, 30], [40], [50]]]