5

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}}
kile
  • 1,671
  • 5
  • 10

5 Answers5

8
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}]]

enter image description here

Bob Hanlon
  • 157,611
  • 7
  • 77
  • 198
5

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}}}

kglr
  • 394,356
  • 18
  • 477
  • 896
4

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}}
Hossein Hadi
  • 635
  • 5
  • 11
4

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}]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
3

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.

Edmund
  • 42,267
  • 3
  • 51
  • 143