# Binning sequential sets of elements together in a list

Given a list of the form:

{{1,2,3,4,5},{6,7,8,9,10},{11,12},{13,14,15,16},{17,18,19,20,21,22,23},{24},{25,26},{27},{4}}


How can I bin each sequential set of N elements of the list together? For example, if N = 3, we would transform the above list into:

{{1,2,3,4,5,6,7,8,9,10,11,12},{13,14,15,16,17,18,19,20,21,22,23,24},{25,26,27,4}}


Of length 3.

-
You could use Partition and Join. –  b.gatessucks Sep 13 '13 at 11:22
@b.gatessucks So apply Partition with the desired value of N, and then flatten each of the new elements? –  HStoley Sep 13 '13 at 11:24
e.g. like so: Join @@@ Partition[list, 3], but depends a lot on what you plan to do –  Pinguin Dirk Sep 13 '13 at 11:25
@b.gatessucks Is there an easy command to apply Flatten[ ,1] to each element in the list? –  HStoley Sep 13 '13 at 11:25
@PinguinDirk Ah, I see, that makes sense. –  HStoley Sep 13 '13 at 11:25

Let

list={{1,2,3,4,5},{6,7,8,9,10},{11,12},{13,14,15,16},
{17,18,19,20,21,22,23},{24},{25,26},{27},{4}}


Thanks to @b.gatessucks, you could either:

 Join @@@ Partition[list, 3]


or

 Flatten /@ Partition[list, 3]


both return:

{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}, {25, 26, 27, 4}}

Note that depending on the initial structure of list, maybe "unexpected" results might occur, e.g. try the following (dropping the last element, i.e. {4}):

Flatten /@ Partition[Most@list, 3]


{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}}

Why? Most@listnow only has 8 elements, thus it is hard to partition in groups of three. By standard, Partition only returns the "full" (i.e. consisting of 3 elements) lists.

To react, you could e.g. use:

Flatten /@ Partition[Most@list, 3, 3, 1, {}]


{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}, {25, 26, 27}}

See the documentation of Partition for more information.

Also, check out the dynP function by Mr.Wizard!

-

Try!

Partition[Flatten@#1, #2, #2, 1, {}] & @@ {list, 12}

-