Python – How to Divide List into Sublists of Unequal Length

listpython

I am trying to divide a list of elements which are comma separated into chunks of unequal length. How can I divide it?

list1 = [1, 2, 1]
list2 = ["1.1.1.1", "1.1.1.2", "1.1.1.3", "1.1.1.4"]

list1 contains the elements which are the sizes of chunks which I wish to divide the list2 in.

Best Answer

You could combine the power of itertools.accumulate and list comprehensions:

In [4]: from itertools import accumulate

In [5]: data = ["1.1.1.1", "1.1.1.2", "1.1.1.3", "1.1.1.4"]

In [6]: lengths = [1, 2, 1]

In [7]: [data[end - length:end] for length, end in zip(lengths, accumulate(lengths))]
Out[7]: [['1.1.1.1'], ['1.1.1.2', '1.1.1.3'], ['1.1.1.4']]

itertools.accumulate returns an iterator to a sequence of accumulated sums. This way you could easily calculate the end of each chunk in the source array:

In [8]: list(accumulate(lengths))
Out[8]: [1, 3, 4]