# A list of operators in the For cycle

I'm pretty sure that analogous questions have been asked here a zillion of times, but...

I think it is pretty straightforward from the code what I expect it to give:

oplist[] := Module[{op, list = {}, k},
For[k = 1, k <= 3, k++,
AppendTo[list, Function[x, x^k]];
];
For[k = 4, k <= 5, k++,
AppendTo[list, Function[x, x^k]];
];
Return[list];
];
list = oplist[];
For[k = 1, k <= Length[list], k++,
Print[list[[k]][a]];
];


Instead of a, a^2, a^3... I have a^6, a^6, a^6... I guess, it's something about pointers/links/evaluating at the moment when smth is called.

I tried replacing x^k with x^Evaluate[k], but this does not help either.

• Try this: f[x_] := x^Range This gives a list of the functions you appear to want. If you want t evaluate at a, then f[a] gives your list {a, a^2, a^3, a^4, a^5}. – bill s Nov 1 '18 at 21:50
• Or if you need them to be operators then oList = With[{k = #}, #^k &] & /@ Range@5 which can then be invoked with Through@oList@a . – Edmund Nov 1 '18 at 22:08

Attributes[Function]


{HoldAll, Protected}

That is, all arguments to Function are to be maintained in an unevaluated form. So x^k in Function[x, x^k] is not evaluated unless it is wrapped with Evaluate:

ClearAll[k, x, a, oplist]
oplist[] :=  Module[{op, list = {}, k},
For[k = 1, k <= 3, k++,
AppendTo[list, Function[x, Evaluate[x^k]]];];
For[k = 4, k <= 5, k++,
AppendTo[list, Function[x, Evaluate[x^k]]];];
Return[list];];

list = oplist[];
For[k = 1, k <= Length[list], k++, Print[list[[k]][a]];]; Alternatively, use With[{j = k}, AppendTo[list, Function[x, x^j]]] in place of AppendTo[list, Function[x, Evaluate[x^k]]].

just remove k from

 Module[{op, list = {}, k}


this will get it right. no other changes in your code

oplist[] :=
Module[{op, list = {}},
For[k = 1, k <= 3, k++, AppendTo[list, Function[x, x^k]]];
For[k = 4, k <= 5, k++, AppendTo[list, Function[x, x^k]]];
Return[list]]
list = oplist[]
For[k = 1, k <= Length[list], k++, Print[list[[k]][a]];];

• Could you please explain why it happens like that? In general, should I never list cycle indices inside the list of local objects? Will they not interfere with the indices defined outside of the Module? – mavzolej Nov 1 '18 at 22:05
• k is defined inside For... Why do you use 2 For-loops instead of one? – J42161217 Nov 1 '18 at 22:10
• The question arises from a more general context, where different cycles inside Module cannot be combined into one, and the outcome of the procedure so far depends on order of cycles inside it. – mavzolej Nov 1 '18 at 22:11
• Please see my question here. – mavzolej Nov 1 '18 at 23:19