1
$\begingroup$

The following works fine to define an element of a two-argument list:

T[1, 2] = {3, 4, "yes"}

But when I try to change the third part, like this

T[1, 2][[3]] = "no"

I get the error message

Set::setps: T[1,2] in the part assignment is not a symbol.

The same message also appears if I go

If[T[1,2][[3]] == "yes", Print["hello"]]

The program doesn't print "hello". It goes

Set::setps: T[1,2] in the part assignment is not a symbol.

I am not an advanced user. What is the simplest way to change this part, so that T[1,2], which was originally {3,4,"yes"} changes to {3,4,"no"}; or to refer to it in the first part of an If statement?

$\endgroup$
2
  • 6
    $\begingroup$ T[1,2] is not a symbol. From the documentation: "Part assignments are implemented only for parts of the value of a symbol." Use ReplacePart[T[1,2],3->"No"] for example. $\endgroup$ – ciao Nov 17 '20 at 0:55
  • 1
    $\begingroup$ @ciao - Thanks for this. It gets rid of the error message, and T[1, 2] = {3, 4, "yes"}; ReplacePart[T[1, 2], 3 -> "No"] yields {3, 4, "no"}. But T[1, 2] = {3, 4, "yes"}; ReplacePart[T[1, 2], 3 -> "No"]; T[1, 2] yields {3, 4, "yes"}. It's as if it only works momentarily. Edit: ah, I get it now: ReplacePart[] is an expression, so I should go T[1, 2] = {3, 4, "yes"}; T[1, 2]=ReplacePart[T[1, 2], 3 -> "No"]. That works fine now. $\endgroup$ – ruffle Nov 17 '20 at 1:40
2
$\begingroup$

You could write your own function:

ClearAll[setPart];
SetAttributes[setPart, HoldAll];
setPart[Part[x_, part__], y_] := x = ReplacePart[x, {part} -> y];

tt[1, 2] = {1, 2, "yes"};

setPart[tt[0, 2][[3]], "no"];

tt[0, 2]
(*  {1, 2, "no"}  *)

You could use a symbol with no built-in meaning:

ClearAll[LeftArrow];
SetAttributes[LeftArrow, HoldAll];
LeftArrow[Part[x_, part__], y_] := x = ReplacePart[x, {part} -> y];

tt[1, 2] = {1, 2, "yes"};

tt[1, 2][[3]] ← "no";

tt[1, 2]
(*  {1, 2, "no"}  *)

LeftArrow () can be entered with ESC < - ESC.

$\endgroup$

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