Replacing specific elements of a nested list

I've a nested list L generated by:

L=Tuples[{{1, 1}, {0, 0}, {1, 0}, {0, 1}}, {n, n}]


For instance, an element of this list is:

$\left( \begin{array}{cc} \{0,1\} & \{1,1\} \\ \{0,1\} & \{1,1\} \\ \end{array} \right).$

Now, for each element of the list $s$, consider for instance the two elements in positions $\{s,1,1,1\}$ and $\{s,2,1,1\}$, in other words the two $0$ in the example above. I'm able to extract those element using:

L[[s]][[All, 1]][[All, 2]]


which delivers $\{0,0\}$.

Here is the question. How do I replace, for all elements of $s$, the sub-elements in those two positions with a new vector, say ${0,1}$?

Note that the example above the element $s$ of $L$ would now look as:

$\left( \begin{array}{cc} \{0,1\} & \{1,1\} \\ \{1,1\} & \{1,1\} \\ \end{array} \right).$

I have tried to use

L[[s]][[All, 1]][[All, 2]]={0,0}


but this returns error

Part specification PR[[1,1,All,All,1]] is longer than depth of object.

I've had no better luck using ReplaceParts.

• (when I try to post the latex code for the matrix I'm asked to indent it as if it were code) Apr 25, 2017 at 13:27
• btw your above code L[[s]][[All, 1]][[All, 2]] should deliver {1,1} and not {0,0} Apr 25, 2017 at 14:34
• yes you are right, thanks. Apr 26, 2017 at 14:22

2 Answers

Use a single Part command:

L=Tuples[{{1,1},{0,0},{1,0},{0,1}},{2,2}];
L[[205]]

L[[205, All, 1, 1]] = {a, b};
L[[205]]


{{{0, 1}, {1, 1}}, {{0, 1}, {1, 1}}}

{{{a, 1}, {1, 1}}, {{b, 1}, {1, 1}}}

• thanks, this looks similar to Ali's answer Apr 26, 2017 at 14:26
L = Tuples[{{1, 1}, {0, 0}, {1, 0}, {0, 1}}, {2, 2}];
Position[L, {{{0, 1}, {1, 1}}, {{0, 1}, {1, 1}}}];
(*{{205}}*)
L[[205]]
(* {{{0,1},{1,1}},{{0,1},{1,1}}}*)

L[[205]][[All, 1]][[1]] = {0, 1}; (* here we replace *)

L[[205]]
(* {{{0,1},{1,1}},{{1,1},{1,1}}} *)

• @Bastiani, please have a look at this Apr 25, 2017 at 19:15
• thanks again. this is working. i just now need to iterate over all tuples. what i don't get is why you assign the value susing L[[205]][[All, 1]][[1]] = {0, 1} but you call the values using L[[205]][[All, 1]][[All,1]] Apr 26, 2017 at 14:26