1
$\begingroup$

This question already has an answer here:

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.

Thanks in advance!

$\endgroup$

marked as duplicate by Kuba, bbgodfrey, Bob Hanlon, rcollyer, Karsten 7. Apr 15 '15 at 12:43

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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

Here's one approach:

sublists = {{1,1,1},{2,2},{3,3,3,3}}
list = {4,5,6}
Map[Flatten,Transpose@{sublists,list},{-3}] (* inline-edit: please, please, don't use this *)
(* {{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];

First@Timing@MapThread[Append,{sublists,list}]
(* 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)

$\endgroup$

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