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 Answers 2

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
  • 2
    $\begingroup$ Or list2[[;; , -1]] += list1. $\endgroup$ Commented Jul 6, 2018 at 10:24
  • $\begingroup$ True, much nicer :) $\endgroup$ Commented Jul 6, 2018 at 10:24

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.