Search code examples
pythonlistsplitchunks

How to split a list in n sized chunks, where n is an iterable list of integers?


I have a list of words and a list of integers 'n'. How do I split the list of words in 'n' sized chunks (uneven)?

e.g.

words = ['apple', 'orange', 'oof', 'banana', 'apple', 'cherries', 'tomato']
n = ['2', '1', '4']

output:

[['apple', 'orange'], ['oof'], ['banana', 'apple', 'cherries', 'tomato']]

Solution

  • Another answer:

    output = []
    count = 0
    for i in range(len(n)):
        chunk_size = int(n[i])
        chunk = []
        for j in range(chunk_size):
            index = (i * j) + j
            chunk.append(words[count])
            count = count + 1
        output.append(chunk)
    
    print(output)