# Transforming a list to list of lists using a specific rule

Say, we have a list: l = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14} and a corresponding list: v = {2,3,2,3,4}. We want to split l into sublists of certain length of consecutive elements ofl and v basically tells us what that length should be. So, in this case, our output would be:

{{1,2},{3,4,5},{6,7},{8,9,10},{11,12,13,14}}


I have written a function that works:

g[l_List] := Module[{split},
split =Table[, {i,1,Length @ l}];
split[[1]] = Table[i,{i,1,First @ l}];
Table[split[[i+1]] = Table[j,{j,Last @ split[[i]] + 1 ,Total @ l[[1;;i+1]]}],
{i,1,Length@l - 1}];
split
]

g@v


{{1, 2}, {3, 4, 5}, {6, 7}, {8, 9, 10}, {11, 12, 13, 14}}

But I'm sure this could be done in a nicer, and more importantly, more efficient way. Any hints?

• It might be worth thinking about what happens when Total@v does not equal Length@l. May 8 '19 at 12:07
• In my case that is always the case, but yeah, it's a valid point. May 8 '19 at 12:19

you can use this built-in

 TakeList[l,v]


{{1, 2}, {3, 4, 5}, {6, 7}, {8, 9, 10}, {11, 12, 13, 14}}

the above solution works with version 11.3

If you have an older version try

FoldPairList[TakeDrop,l,v]


{{1, 2}, {3, 4, 5}, {6, 7}, {8, 9, 10}, {11, 12, 13, 14}}

• Brilliant, thank you! May 8 '19 at 10:34