Add elements of one list to sublists of another list [duplicate]

I have the following list of sublists with different lengths {{1,1,1},{2,2},{3,3,3,3}} and a second list {4,5,6}with the same number of elements as I have sublists in the first list.

I would like to add the elements of the second list as last elements to each sublist. The result should look like this: {{1,1,1,4},{2,2,5},{3,3,3,3,6}}

I am looking for a beginner solution to the problem.

• This topic has the answer: 67423. It is marked as a duplicate but I don't think the latter one fits here. – Kuba Apr 15 '15 at 12:01
• you may try MapThread[Append, {{{1, 1, 1}, {2, 2}, {3, 3, 3, 3}}, {4, 5, 6}}] – penguin77 Apr 15 '15 at 12:14

Here's one approach:

sublists = {{1,1,1},{2,2},{3,3,3,3}}
list = {4,5,6}
(* {{1,1,1,4},{2,2,5},{3,3,3,3,6}} *)


Not too great, especially if the elements are non-atomic expressions.

Map[Flatten,Transpose@{sublists,list},{1}]


or

Flatten/@(Transpose@{sublists,list})


seems a safer solution.

Or with Append:

Append@(Evaluate@(Sequence@@#))&/@Transpose@{sublists,list}


I'm still wondering, how to get rid of that Transpose without a loss of the functional approach.

EDIT of course, silly me, I've overlooked MapThread as provided in the linked question.

MapThread[Append,{sublists,list}]


EDIT2 some benchmarking.

sublists = RandomReal[5, {10*^5,5}];
list = RandomInteger[5,10*^5];

(* 1.154407 *)

First@(Timing@(Append@(Evaluate@(Sequence@@#))&/@Transpose@{sublists,list}))
(* 3.057620 *)

First@Timing@(Flatten/@Transpose@{sublists,list})
(* 2.012413 *)


Obviously MapThread (as also provided now in the comments) is the way to go.

More options

As in my first two approaches Flatten performed better than Append, I figured, there must be a better way.

First@Timing@MapThread[Flatten[{##}]&, {sublists,list}]
(* 2.589617 *)


(deleted approach with Join, as it was incorrect, corrected version doesn't improve speed, will look for other fast methods)