# How to set a particular element of a list to a number?

I have a list {a,b,c,d}, and I want to set the 1st element and the 3rd elements equal to 5 and 8, respectively, leaving 2nd and 4th as they are ({b,d} used later). How is this done?

Later, I want to set the 2nd element and the 4th element to other numbers, then 1st and 2nd, and so on... I spent a lot of time working on this (yup, embarrassed) but cant find a solution.

• If list = {a, b, c, d}, then do list[[{1, 3}]] = {5, 8} etc. Apr 23 '18 at 18:33
• Yes, but it doesn't set a and c equal to 5 and 8, respectively. I want to assign 5 to a, and 8 to c (but in list form). How is that done? Apr 23 '18 at 18:38
• So you want to set the value of those symbols a/c? Do you want this to work once they have values etc?
– Kuba
Apr 23 '18 at 19:19
• list /. {a->5, c->8}? Apr 23 '18 at 19:36
• Hi Kuba, Yes, and a & c (elements of the list) are randomly chosen - they can, on next iteration be b & d, too... Apr 23 '18 at 20:01

It is better to use indexed variable for this kind of manipulations. See related topics for a background of what is about to happen: 40663, 70250.

You can do:

set // Attributes = {HoldFirst};
set[varList_, pos_, values_] := (
Hold[varList] /. OwnValues[varList]
)[[{1}, pos]] /. Hold[vars_] :> Hold[vars = values] // ReleaseHold


Which is far from being neat but it works.

{a, b, c, d, e} = Range;
varList := {a, b, c, d, e};

varList

set[varList, {1, 3}, {15, 15}];
varList

set[varList, 2 ;;, {1, 11, 111, 111}];
varList

{1, 2, 3, 4, 5}

{15, 2, 15, 4, 5}

{15, 1, 11, 111, 111}


As Kuba mentioned, it is better to use an indexed variable, so here are a couple of examples.

Clear[i]

list = i /@ Range

{i, i, i, i}

(i[#1] = #2) & @@@ {{1, 5}, {3, 8}};

i /@ Range

{5, i, 8, i}

Clear[x]

With[{x = i /@ {2, 4}}, x = {7, 9}];

list

{5, 7, 8, 9}

Array[i, 4]

{5, 7, 8, 9}