# Get a List With Partition

How can I add two brackets for a sublists of Length 2 ?

Objective:

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

The code I write here only give only 1 bracket for a sublist of length 2

Input:

Partition[Table[i, {i, 18}], 2]

Output:

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

• Try Map[{#} &, Partition[Table[i, {i, 18}], 2]] Commented Dec 22, 2019 at 13:18
• Thanks. Any other way to work it out?@UlrichNeumann
– kile
Commented Dec 22, 2019 at 13:24
• ArrayReshape[Table[i, {i, 18}], {9, 1, 2}] Commented Dec 22, 2019 at 13:33
• @BobHanlon, Great work!
– kile
Commented Dec 22, 2019 at 13:45

Clear["Global*"]

\$HistoryLength = 0;


The two methods produce identical results

With[{n = 1000},
List /@ Partition[Range[n], 2] ===
ArrayReshape[Range[n], {n/2, 1, 2}]]

(* True *)


Comparing timings

timing1[n_Integer?Positive] :=
RepeatedTiming[List /@ Partition[Range[n], 2];][[1]]

timing2[n_Integer?Positive] :=
Module[{data = Range[n]},
RepeatedTiming[ArrayReshape[data, {Length[data]/2, 1, 2}];][[1]]]

ListLogLogPlot[{
{#, timing1[#]} & /@ (10^Range[7]),
{#, timing2[#]} & /@ (10^Range[7])},
Joined -> True,
Frame -> True,
FrameLabel -> (Style[#, 14, Bold] & /@
{"number of elements",
"timing"}),
PlotLegends ->
Placed[{"Partition and Map", ArrayReshape}, {.35, .75}]]


Slower than ArrayReshape but ... there is also

BlockMap

BlockMap[List, Range@18, 2]


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

and the (undocumented) 6-argument form of Partition:

Partition[Range@18, 2, 2, 1, {}, {{##}} &]


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

Trying with patterns is very easy in order to handle all that stuff.

If you have defined list = Partition[Table[i, {i, 19}], UpTo[2]] , you could obtain your preferred result in two different ways :

First :

list /. (a_List)?(Length[#] == 2 &) :> {a}


Second and much simpler :

Partition[Table[i, {i, 18}], 2] /. {a_, b_} :> {{a, b}}


Possibly what you are looking for:

First @ Partition[{Range[18]}, {1, 2}]

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


Note the extra { } around Range[18] to make it two dimensional.

Or Partitioning sequentially:

Fold[Partition, Range[18], {2, 1}]


You may use Partition and Transpose with TwoWayRule.

Transpose[{Partition[Range@18, {2}]}, 2 <-> 1]

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


TwoWayRule was introduced in version 11.2 so if you have an earlier version than the following is equivalent.

Transpose[{Partition[Range@18, {2}]}, {2, 1, 3}]
`

Hope this helps.