3
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ If list = {a, b, c, d}, then do list[[{1, 3}]] = {5, 8} etc. $\endgroup$ – Carl Woll Apr 23 '18 at 18:33
  • $\begingroup$ 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? $\endgroup$ – Nari Nare Apr 23 '18 at 18:38
  • $\begingroup$ So you want to set the value of those symbols a/c? Do you want this to work once they have values etc? $\endgroup$ – Kuba Apr 23 '18 at 19:19
  • $\begingroup$ list /. {a->5, c->8}? $\endgroup$ – AccidentalFourierTransform Apr 23 '18 at 19:36
  • $\begingroup$ Hi Kuba, Yes, and a & c (elements of the list) are randomly chosen - they can, on next iteration be b & d, too... $\endgroup$ – Nari Nare Apr 23 '18 at 20:01
1
$\begingroup$

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[5];
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}
$\endgroup$
0
$\begingroup$

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

Clear[i]

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

i /@ Range[4]
{5, i[2], 8, i[4]}
Clear[x]

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

list
{5, 7, 8, 9}
Array[i, 4]
{5, 7, 8, 9}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.