# How can I replace part of list and have the replacement affect the initial list?

I have a list:

list = {{1,1,0.05,0.05}, {2,2,0.05,0.05}};


and I want to do this change

Replace[#[[1]], #[[1]] -> (#[[1]] + #[[3]])]& /@ list
Replace[#[[2]], #[[2]] -> (#[[2]] + #[[4]])]& /@ list


The problem is that the initial list doesn't change.

My list represents $\{\{x, y, v_x, v_y\}, \{x, y, v_x, v_y\}\}$ and I want to use a replacement rule to change the position of the objects and thereby represent movement.

I'd recommend to apply certain function (here you'd like {#1 + #3, #2 + #4, #3, #4} &) at the level 1 of the list ( f @@@ list is a shorthand for Apply[ f, list, {1}]). So here a good way is :

list = {{1, 1, 0.05, 0.05}, {2, 2, 0.05, 0.05}};

list = {#1 + #3, #2 + #4, #3, #4} & @@@ list

{{1.05, 1.05, 0.05, 0.05}, {2.05, 2.05, 0.05, 0.05}}


If you want to play with ReplaceAll you can try another approach, e.g. this :

list = list /. {a_, b_, c_, d_} -> {a + c, b + d, c, d}


it yields the same list :

(list /. {a_, b_, c_, d_} -> {a + c, b + d, c, d}) == ({#1 + #3, #2 + #4, #3, #4} & @@@ list)

True


I think the problem is that you may have misunderstood the meaning of Replace. It doesn't replace anything in the sense of modifying the object on which it acts. It produces a new object. So what you really want to do if you want list to change is this:

list = {{1, 1, 0.05, 0.05}, {2, 2, 0.05, 0.05}}

(* ==> {{1, 1, 0.05, 0.05}, {2, 2, 0.05, 0.05}} *)

list = {#[[1]] + #[[3]], #[[2]] + #[[4]], #[[3]], #[[4]]} & /@
list

(* ==> {{1.05, 1.05, 0.05, 0.05}, {2.05, 2.05, 0.05, 0.05}} *)


Then you can repeatedly apply the last assignment to represent the movement in the first two components.

Here I have explicitly assigned the result of the Map operation on list back to the variable list itself by using Set (list = ...).