# How to update a list in a function in each iteration

There is a list with numbers 1 to 8 ( p1 ) and another list (j) which contains 4 numbers which shows different 4 positions of the elements in list p1. I want to take 4 elements from p1 related to the 4 numbers of positions from the list j and multiply those selected 4 numbers from list p1 by 2.

The code below is a function that do the procedure that I have mentioned above :

p1 = {1, 2, 3, 4, 5, 6, 7, 8};

DoMul[p1_] := Module[{nmu, e1, j, mul, Replacement},
j = {1, 6, 7, 8};
i = 1; While[i <= 4,
e1 = Extract[p1, {j[[i]]}];
mul = 2*e1;
Replacement = ReplacePart[p1, j[[i]] -> mul];
; i++];
Replacement];


The problem is that I do not know how to update p1 in each iteration ( There are 4 iterations ) and the result will be :

{1, 2, 3, 4, 5, 6, 7, 16}


but the correct answer must be :

{2, 2, 3, 4, 5, 12, 14, 16}


Does anyone know how to update the p1 list in each iteration?

-

p1 = {1, 2, 3, 4, 5, 6, 7, 8};
j = {1, 6, 7, 8};

p1[[j]] *= 2;
p1

(* {2, 2, 3, 4, 5, 12, 14, 16} *)


Replacing your function (I assume you want to keep the argument/original unchanged and return the changed version):

p1 = {1, 2, 3, 4, 5, 6, 7, 8};

domul[p1_] := Module[{replacement = p1, j = {1, 6, 7, 8}},
replacement[[j]] *= 2;
replacement];

domul[p1]

(* {2, 2, 3, 4, 5, 12, 14, 16} *)


Also note I changed things to lowercase - bad idea in general to use uppercase initials, might clash with Mathematica built-in symbols.

-
@RunnyKine: LOL - grabbed a coffee, did not see yours. If you'd like this too-similar result deleted, no worries....and a +1 on yours for penance. –  rasher Apr 1 at 10:07
Lol. The more the merrier. –  RunnyKine Apr 1 at 10:17
@ rasher : I used it and it properly worked out of the function. But it doesn't work when I use it inside the function DoMul[p1_]. Could you please elaborate what the problem is ?! –  Shellp Apr 1 at 10:53
@Shellp: see update. Let me know if further clarification needed. –  rasher Apr 1 at 11:06
@ rasher : many thanks for it!! –  Shellp Apr 1 at 11:07

Just do the following:

p1[[j]] = 2 p1[[j]]


Then p1 gives:

{2, 2, 3, 4, 5, 12, 14, 16}

-

Redundant way :

Fold[MapAt[2 # &, #1, #2] &, p1, j]

-
@ esprit Thank you esprit!! It's a brilliant way !! –  Shellp Apr 1 at 11:06
MapAt could also be used Fold-lessly here: MapAt[2 # &, p1, List /@ j] –  Aky Apr 1 at 11:50
@Aky : Yes, indeed! –  esprit Apr 1 at 12:12