# Create a list of indexed variables and assign values in one line of code

It is easy to create a list of indexed variables

F/@{1,3,6,8}


I would like to assign values in the same line of code

F/@{1,3,6,8}={2,4,6,0}


but it complains Set::write: Tag Map in F/@{1,3,6,8} is Protected. Why, whats going on?

index = {1, 3, 6, 8};

values = {2, 4, 6, 0};


Create an Association

data = <|Rule @@@ Transpose[{index, values}]|>


<|1 -> 2, 3 -> 4, 6 -> 6, 8 -> 0|>

Define a Lookup-function

F[i_] := Lookup[data, i, {}]


The 3rd parameter of Lookup replaces missing keys

F[-1]


{}

F[1]


2

F[{1, 3, -1}]


{2, 4, {}}

Evaluate[F /@ {1, 3, 6, 8}] = {2, 4, 6, 0}

• @PhillipDukes - As shown, since Set has the attribute HoldFirst, you must Evaluate the LHS Commented Nov 10, 2023 at 22:01

another method:

F = AssociationThread[{1, 3, 6, 8} -> {2, 4, 6, 0}]
F[1]


2

Clear[F]
MapThread[Set,{F /@ {1, 3, 6, 8}, {2, 4, 6, 0}}];
F /@ {1, 3, 6, 8}

(* {2,4,6,0} *)


Just another way:

Clear@F;
Set @@ {F /@ {1, 3, 6, 8}, {2, 4, 6, 0}};

DownValues@F
(*{HoldPattern[F[1]] :> 2, HoldPattern[F[3]] :> 4, HoldPattern[F[6]] :> 6, HoldPattern[F[8]] :> 0}*)

F /@ {1, 3, 6, 8}
(*{2, 4, 6, 0}*)