8
$\begingroup$

I an aware of the Partition command which partitions a list into sublists. I'm curious as to whether there is an efficient way to partition a list several times over in one step. For example, can I turn the list

{1,2,3,4,5,6,7,8}

into the list

{{{1,2},{3,4}},{{5,6},{7,8}}}

through one use of the Partition command instead of two (or indeed any command). In actual fact, I'll be going to a list of many levels of nested lists, which is why I'm keen to know the answer. Thanks in advance for any help.

$\endgroup$
0

1 Answer 1

10
$\begingroup$

Try ArrayReshape:

ArrayReshape[{1, 2, 3, 4, 5, 6, 7, 8}, {2, 2, 2}]
{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}

or Fold+ Partition:

Fold[Partition, Range[8], {2, 2}]
{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}

or Nest + Partition:

Nest[Partition[#, 2] &, Range @ 8, 2]
 {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}

There is also the (undocumented) 6-argument of form of Partition:

Partition[Range @ 8, 4, 4, 1, {}, Partition[{##}, 2] &]
 {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.