# Replace parts of nested lists

I have list of stock data as follows:

lis1=
{{{1992/10/12, 126.946, AEX}, {1992/10/13, 127.85, AEX}},
{{1992/10/12, 88.487, AFLI},{1992/10/13, 91.825, AFLI}}}


I would like to replace the closing prive (second entry in each nested list) with the corresponding value of the following list. Both lists have the same lengths.

lis2=
{{125.12,125.32},{91.34,91.88}}


Does anyone have a hint?

• Possible duplicate: (3069) Apr 24, 2015 at 16:42

For in-place modification use assignment to Part:

lis1[[All, All, 2]] = lis2;

lis1

{{{83/5, 125.12, AEX}, {996/65, 125.32, AEX}},
{{83/5, 91.34, AFLI}, {996/65, 91.88,  AFLI}}}


If you do not want to modify lis1 make a copy first and use the same syntax.

Automation of the copy operation:

(newPart[expr_, part___] = new_) ^:= Module[{x = expr}, x[[part]] = new; x]


(Syntax highlighting may complain but the definition still works.)

Usage example:

(* starting with original lis1 definition *)

newPart[lis1, All, All, 2] = lis2

{{{83/5, 125.12, AEX}, {996/65, 125.32, AEX}},
{{83/5, 91.34, AFLI}, {996/65, 91.88, AFLI}}}


lis1 remains unchanged:

lis1

{{{83/5, 126.946, AEX}, {996/65, 127.85, AEX}},
{{83/5, 88.487, AFLI}, {996/65, 91.825, AFLI}}}

• is there an elegant way to do that without making a copy? Aug 4, 2015 at 14:23
• @garej In my opinion making a copy is the best approach. It is easy to write a utility function to automate this; I'll append that to my answer for your consideration. Aug 4, 2015 at 18:34
• thank you, I see. In my case I have a matrix, (re)generated by random process (in Dynamic setting). Is it fine to make a copy of it as it changes each time something else changes? Aug 5, 2015 at 9:02
• @garej In your position I would try it and see. I think memory management and garbage collection should allow that to work. The way you describe that however it sounds like you could use in-place modification. I wonder what the need for a copy with every change is? Aug 6, 2015 at 4:10