For

For

For[ var, list ] ... End executes a script block once for each element of a list.

Usages

For[ var, list ] ... End

Executes the script between For and End once for each element of list. In each iteration, var has the value of the next element. list can be a list or a set, written directly or stored in a script variable.

Example in out
The sum of the elements of a list. list := {1, 3, 5, 7}
sum := 0
For[ii, list]
  sum := CalcPlus[sum, ii]
End
sum = 16
Execute a block 10 times, using Range[10] = {1, 2, ..., 10}. s := 0
For[ii, Range[10]]
  s := CalcPlus[s, ii]
End
s = 55
Build a new list. L := {}
For[ii, {1, 2, 3}]
  L := Concat[L, CalcPower[ii, 2]]
End
L = {1, 4, 9}
The elements can be any expression. res := 1
For[v, {x, y, z}]
  res := res^v
End
res = ((1^x)^y)^z
Nested loops. s := 0
For[ii, {1, 2}]
  For[jj, {10, 20}]
    s := CalcPlus[s, CalcTimes[ii, jj]]
  End
End
s = 90
Details
  • After the loop, var keeps the value of the last element.
  • Empty list: For[ii, {}] does not execute the block.
  • Number of iterations: a loop over more than 101 elements stops the script with the error Max iterations reached in For loop.
  • Tip: if the list is the result of a command, store it in a script variable first, and loop over that variable. For example, to loop over the terms of a sum:
    T := Apply[List, a + 2b + c^2]
    For[t, T]
      ...
    End

    Writing the command directly in For, as in For[t, Apply[List, a + 2b + c^2]], can stop the script with the error index out of bounds.
Invalid input Result
For[ii, 5] ... End Error: the 2nd argument is not a valid collection
For[t, a+b+c] ... End Error. Loop over a list of the terms instead (see the tip above).
Warning

Do not change the list inside the loop. The loop variable refers to a position in the list, so changing the list gives wrong results or an error. For example, list := {1, 3, 5, 7}
For[ii, list]
  list := {0}
End
stops the script with the error index out of bounds. Build a new list in a separate variable instead, as in the examples above.

See also: While, If, Map, Concat