# Coloring elements in nested list consistently over all sublists

Coloring elements of sublists has been dealt with in another question.

A solution for sublists was presented along the following lines.

Permutations[{1, 2, 3}] //
MapAt[Style[#, Red] &, #, {1, #} & /@ Range[2, 2]] & //
MapAt[Style[#, Blue] &, #, {2, #} & /@ Range[3, 3]] &


This produces the output of a list of permutations {{1,2,3},{1,3,2}, {3,2,1}}, in which the first sublist {1,2,3} has the element 2 (in position 2) colored red and the second sublist {1,3,2} has the element 2 (in position 3) colored blue.

I would like to obtain the result where all sublists have the second element colored red and the third colored blue.

This should be produced regardless of the number of sublists in the list.

Call the coloring function for each sublist using /@.

(MapAt[Style[#, Blue] &, MapAt[Style[#, Red] &, #, 2], 3] &) /@ Permutations[{1, 2, 3}]


Using MapThread:

MapThread[Style[#1, #2] &, {#, {Black, Red, Blue}}] & /@
Permutations[{1, 2, 3}]


Version 12 introduced SubsetMap which is a convenient generalization of MapAt:

SubsetMap[Thread[Style[#, {Red, Blue}]]&, #, {2, 3}]& /@ Permutations[{1, 2, 3}]


An alternative to SubsetMap and MapAt is to modify parts directly:

list = Permutations[{1, 2, 3}];
list[[All, {2, 3}]] = Thread[Style[#, {Red, Blue}]] & /@ list[[All, {2, 3}]];
list


same result

In versions 12.2+, we can also use ApplyTo:

f = Map[Thread@Style[#, {Red, Blue}] &];

list = Permutations[{1, 2, 3}];
list[[All, {2, 3}]] //= f;
list


Using SequenceReplace:

l = Permutations[Range[3]];
colors = {Black, Red, Blue};

Map[Style[#[[1]], #[[2]]] &, SequenceReplace[l, {x_} :> Transpose@{x, colors}],{2}]


Or using SequenceReplace and ReplaceAll:

SequenceReplace[l, {x_} :> Transpose@{x, colors}] /. {x_, y_} :> Style[x, y]


Edit:

Thanks, @Syed, for your kindly suggestion:

Transpose[{#, colors}] & /@ l /. {a_, b_} :> Style[a, b]

• Simpler: Transpose[{#, colors}] & /@ l /. {a_, b_} :> Style[a, b]
– Syed
Apr 16, 2023 at 14:59
a = Permutations[{1, 2, 3}];

c = {Black, Red, Blue};


Using ReplacePart

ReplacePart[a, {i_, j_} :> Style[a[[i, j]], c[[j]]]]