1

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!

Niki
  • 960
  • 4
  • 14

1 Answers1

1

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)

LLlAMnYP
  • 11,486
  • 26
  • 65