# Merging one element into a two-element list

I am trying to find how can do this really quick:

list = {{a, b}, c, {d, e}, f, {g, h}, i}

Desired output List is:

{{a,b,c},{d,e,f},{g,h,i}}

Looks like simple but it takes me plenty of time to think... sorry if this one has been asked before, I didn't find any answer yet.

• BTW, you cannot set values to List. Dec 5, 2017 at 3:44
• Yes, that's a typo, thanks for pointing it out! Dec 5, 2017 at 14:10

Also:

Append @@@ Partition[list, 2]
ArrayReshape[list, {3, 3}]
SequenceReplace[{{x_, y__}, z_} :> {x, y, z}]@list
Flatten /@ Partition[list, 2] (* thanks: Okkes Dulgerci *)
{## & @@ #, #2} & @@@ Partition[list, 2]


all give

{{a, b, c}, {d, e, f}, {g, h, i}}

Update: You can also use the undocumented 6th argument of Partition:

Partition[list, 2, 2, {1, -1}, {}, Append]


{{a, b, c}, {d, e, f}, {g, h, i}}

• Out of these 3 methods, I'm guessing that ArrayReshape would be the most efficient, right? Dec 5, 2017 at 10:52
• Thank you! Great answers! Dec 5, 2017 at 14:03
• @SjoerdSmit, sorry for late response. Yes, based on limited tests ArrayReshape and Append+Partition combination are the fastest of the four methods.
– kglr
Dec 20, 2017 at 5:13
• Flatten /@ Partition[list, 2] Nov 10, 2018 at 2:06
• Thank you @OkkesDulgerci.
– kglr
Nov 10, 2018 at 21:35
BlockMap[Flatten, list, 2]


Of course, the BlockMap also can be DeveloperPartitionMap

• This should be the most concise one. Dec 5, 2017 at 8:49
• Thank you, sir! Dec 5, 2017 at 14:08

If the input list is consistently dimensioned, then this would work:

list = {{a, b}, c, {d, e}, f, {g, h}, i};
Partition[ Flatten[list, 1], 3]


I hope that this gets you what you need.

• yes, the pattern is consistent. Thanks for your help, this is work! Dec 5, 2017 at 3:28
• Partition[Flatten[list], 3] is enogh
– yode
Dec 5, 2017 at 9:11

Method I

Step by step

Cases[list, _List]
List /@ Complement[list, %]
Join[%%, %, 2]


give respectively

{{a, b}, {d, e}, {g, h}}

{{c}, {f}, {i}}

{{a, b, c}, {d, e, f}, {g, h, i}}


Method II

Flatten /@ Transpose @ GatherBy[list, Head]
`
• Wow, nice illustration! Dec 5, 2017 at 14:04
• @leon365 Glad to be helpful. :) Dec 5, 2017 at 14:09