4
$\begingroup$

I have two lists, where the number of elements of list 1 = number of sublists of list 2:

list1 = {a,b};
list2 = {{f,g,h,i},{j,k,l,m}}

I would like to add elements of list1 to the last elements of list2, so I did

list3 = MapThread[Append,{list2,list1}];

list3 = list3 /. {x1_,x2_,x3_,x4_,x5_} -> {x1,x2,x3,x4+x5}

It works but I suspect there is a more efficient way with, perhaps, MapAt or some combination of functions that I can't figure out. How would you do it? Thanks in advance.

$\endgroup$
2
$\begingroup$

With padding:

list2 + Map[PadLeft[{#},4]&, list1]

{{f, g, h, a + i}, {j, k, l, b + m}}

$\endgroup$
5
$\begingroup$

See code below:

list2[[;; , -1]] = list2[[;; , -1]] + list1;
list2

{{f, g, h, a + i}, {j, k, l, b + m}}

EDIT: or the more compact, suggested by @Henrik Schumacher in the comment below:

list2[[;; , -1]] += list1
$\endgroup$
  • 2
    $\begingroup$ Or list2[[;; , -1]] += list1. $\endgroup$ – Henrik Schumacher Jul 6 '18 at 10:24
  • $\begingroup$ True, much nicer :) $\endgroup$ – Fraccalo Jul 6 '18 at 10:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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