Wolfram Language Fast Introduction for Programmers
Get Started »

Iterators

Not to be confused with Java's Iterator interface, the Wolfram Language's iterator notation reduces the code required for repetitive operations. Generally, these iterators are used for tasks that would require loops in Java.

Make a table of the first 10 squares:

In[1]:=
X
Out[1]=

Many functions in the Wolfram Language use the standard
iterator specification: min, max, step:

In[2]:=
X
Out[2]=

In Java, iterative operations like this would require a for or while loop.

An alternative iterator specification just gives an explicit list of values:

In[3]:=
X
Out[3]=

Using Table this way is analogous to iterating over a Java array or collection with a foreach construct.

Using Table in this way is analogous to using the [ ... for ... in ... ] list comprehension construct in Python, though it has somewhat richer semantics.

This makes a nested table:

In[1]:=
X
Out[1]=
Check Your Understanding

Which of these makes a table of the first 20 numbers?

Table[20, {i, 1, 20}]

Incorrect. Each element would be 20.

Table[i, {i, 1, 20}]

Correct.

Table[i, 20]

Incorrect. The iterator for Table has to be a list.

What is the first element of the list produced by Table[f[x], {x, {3, 4, 6}}]?

f[3, 4, 6]

Incorrect. The list that gets made is {f[3], f[4], f[6]}, so its first element is f[3].

f[1]

Incorrect. The list that gets made is {f[3], f[4], f[6]}, so its first element is f[3].

f[3]

Correct.

Which one of these evaluates to the list of squares {1, 4, 9, 16}?

Table[x^2, 4]

Incorrect. The iterator is the second argument, and it needs to be a list and to specify the variable x.

Table[x^2, {x, 4}]

Correct.

Table[x^2, {x, 0, 4}]

Incorrect. This iterator specifies to begin at 0. 0^2 is 0, which isn't in the target list.