WolframLang: Create List (Table, Range)

By Xah Lee. Date: . Last updated: .

There are a lot functions to create list. The most important one is Table .

Table

Use Table to generate a flat list or nested list (n-dimensional matrix or rectangular array). Like Python list comprehension but more powerful.

Table

Table[expr, n]

a list with expr repeated n times.

Table[ x, {3}] ===
{x, x, x}
Table[expr, {i, iMax}]

a list, each item is expr with the variable i successively taking on the values 1 through iMax (in steps of 1).

Table[ x, {x, 3}] ===
{1, 2, 3}
Table[expr, {i, iMin, iMax}]

start with iMin.

Table[ x, {x, 6, 9}] ===
{6, 7, 8, 9}

Table[ y + x^2, {x, 1, 5}] ===
{1 + y, 4 + y, 9 + y, 16 + y, 25 + y}
Table[expr, {i, iMin, iMax, di}]

use steps di.

Table[ x, {x, 1, 3, 1/2}] ===
{1, 3/2, 2, 5/2, 3}

Table[ x, {x, 1, 3, 0.5}] ===
{1., 1.5, 2., 2.5, 3.}
Table[expr, {i, iMin, iMax, di}, {j, jMin, jMax, dj}, etc]

a nested list. For each i, loop over j, etc.

Table[ {x, y}, {x, 3}, {y, 2}] ===
{{{1, 1}, {1, 2}}, {{2, 1}, {2, 2}}, {{3, 1}, {3, 2}}}
Table[expr, {i, {i1, i2, etc}}}]

a flat list. Each item use the given list of values {i1, i2, etc}.

Table[ x, {x, {3, 9, 2}}] ===
{3, 9, 2}

Table examples

any part can be symbolic

Table[ Sin[x], {x, 0, 2 Pi, Pi/4}] ===
{0, 1/Sqrt[2], 1, 1/Sqrt[2], 0, -(1/Sqrt[2]), -1, -(1/Sqrt[2]), 0}

3-dimensions example

Table[ {x, y, z}, {x, 1, 3}, {y, 8, 9}, {z, 0, 1, 0.5}]
WolframLang 3d matrix 2022-06-03 s3BYV
WolframLang 3d matrix

arbitrary expression

Table[ f[x+y]*z, {x, 3}, {y, 3}, {z, 2}] ===
{
{{f[2], 2*f[2]}, {f[3], 2*f[3]}, {f[4], 2*f[4]}},
{{f[3], 2*f[3]}, {f[4], 2*f[4]}, {f[5], 2*f[5]}},
{{f[4], 2*f[4]}, {f[5], 2*f[5]}, {f[6], 2*f[6]}}}

💡 TIP: Table is the most powerful way to generate a list, and is most used. Master it.

Range

Range
  • range[max]
  • range[min, max]
  • range[min, max, step]

return a flat list.

Like Python range but more powerful. Argument needs not be integer.

Range

Range[5] ===
{1, 2, 3, 4, 5}

(* min to max *)
Range[4, 8] ===
{4, 5, 6, 7, 8}

(* step of 0.5 *)
Range[1, 3, 0.5] ===
{1., 1.5, 2., 2.5, 3.}

(* symbolic step *)
Range[1, 3, 1/2] ===
{1, 3/2, 2, 5/2, 3}

(* negative step *)
Range[1, -1,  -0.5] ===
{1., 0.5, 0., -0.5, -1.}

(* any arg can be symbolic *)
Range[0, 3 Pi,  Pi/2] ===
{0, Pi/2, Pi, (3*Pi)/2, 2*Pi, (5*Pi)/2, 3*Pi}

WolframLang Loop, Iteration, Recursion

List