# Replacing elements of a list using a pure function fails; why?

I have this list:

{{5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}, {25, 26, 27, 28, 29}}

For learning purposes I try to replace one number (random) in each sublist with "a". I try to do it by using a pure function, but I get an error when using this code:

mylist = Range[5 #, 5 # + 4] & /@ Range[5]
i = Random[Integer, {1, 5}]
mylist[[#, i]] & /@ Range[1, 5] = a


Why do I get an error and what should I do instead?

list = Partition[Range[5, 29], 5];

SeedRandom[1]

(list[[#, RandomInteger[{1, 5}]]] = a) & /@ Range@Length@list


or

ReplacePart[list, i_ :> {list[[i, RandomInteger[{1, 5}]]] = a}]


or

MapThread[(list[[##]] = a) &, {Range@5, RandomInteger[{1, 5}, 5]}]


all give

list // MatrixForm


If you want to replace at the same position it would simply be

list[[All, RandomInteger[{1, 5}]]] = a;

list // MatrixForm


The problem is that you are trying to Set the entirety of mylist[[#, i]] & /@ Range[1, 5] to a. This expression really looks like

Map[mylist[[#, i]] &, Range[1, 5]] = a


which means you are trying to associate a definition with Map, which is a protected function, just like

f[something] = a


associates a definition with f. Evaluating the expression first doesn't work either, i.e.

Evaluate[mylist[[#, i]] & /@ Range[1, 5]] = a


because the left-hand side evaluates to {a, a, a, a, a}, which is the same as List[a, a, a, a, a], and then you are trying to associate a definition with List, which is protected as well.

Here's how you would make it work using your idea: (mylist[[#, i]] = a) & /@ Range[1, 5].

Here's the most straight-forward way:

mylist[[All, i]] = a


A better explanation as why was given by march.

(mylist[[#,i]]=a)&/@Range[1,5]

mylist[[Range[1, 5], i]] = a