You seem to have found a solution, but still break it.
First, you have a simple transcription error where your Set applies the original values ββrather than replacing them. The base code works with this change:
i = 2; x = {1, 1, 0, 0}; If[ x[[i]] == 1 && x[[i + 1]] == 0, x[[i]] = 0; x[[i + 1]] = 1; ] x
{1, 0, 1, 0}
So, we have successfully changed x . To do this in a function, we must pass the name x this code, not the value x . This is the source of your error:
{1, 1, 0, 0}[[2]] = 0;
Set :: setps: {1,1,0,0} in the part assignment is not a symbol. β
You need a Hold attribute for your function:
SetAttributes[f, HoldAll] f[i_, x_] := If[x[[i]] == 1 && x[[i + 1]] == 0, x[[i]] = 0; x[[i + 1]] = 1;] i = 2 ; x = {1, 1, 0, 0}; f[2, x] x
{1, 0, 1, 0}
You may not have intended to change the value of x itself, but this method will undoubtedly come in handy in other applications. To change the function above to manage a copy of the data, we can use the Module , and we do not need the Hold attribute:
f2[i_, xImmutable_] := Module[{x = xImmutable}, If[x[[i]] == 1 && x[[i + 1]] == 0, x[[i]] = 0; x[[i + 1]] = 1]; x ] i = 2 ; x = {1, 1, 0, 0}; f2[2, x]
{1, 0, 1, 0}
Note that the x inside the Module is a local variable, not your global list of x , which remains unchanged.
For fun, let it be implemented differently.
f3[i_, x_] := If[ x[[i + {0, 1}]] == {1, 0}, ReplacePart[x, {i -> 0, i + 1 -> 1}], x ] f3[2, x]
{1, 0, 1, 0}