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 = 16 |
Execute a block 10 times, using Range[10] = {1, 2, ..., 10}. |
s := 0 |
s = 55 |
| Build a new list. | L := {} |
L = {1, 4, 9} |
| The elements can be any expression. | res := 1 |
res = ((1^x)^y)^z |
| Nested loops. | s := 0 |
s = 90 |
Details
- After the loop,
varkeeps 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 inFor, as inFor[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} stops the script with the error index out of bounds. Build a new list in a separate variable instead, as in the examples above.
For[ii, list]
list := {0}
End