Lists
Prerequisites: Everything is an expression
A list holds values in order, written with curly braces. Lists are the Wolfram Language's workhorse: vectors, matrices, tables, and data are all lists.
Creating lists
{10, 20, 30}
Range[5]
Range[2, 10, 2]
Range[0, 1, 0.25]
Table[i^2, {i, 5}]
Table[i + j, {i, 2}, {j, 3}]
{10, 20, 30}
{1, 2, 3, 4, 5}
{2, 4, 6, 8, 10}
{0., 0.25, 0.5, 0.75, 1.}
{1, 4, 9, 16, 25}
{{2, 3, 4}, {3, 4, 5}}
Range[start, end, step]—0.and1.are approximate numbers because the step was.Table[expr, {i, n}]evaluatesexprforifrom 1 ton.{i, a, b}and{i, a, b, step}also work, and several iterators make nested lists.
Getting parts
list = {10, 20, 30, 40, 50};
list[[1]]
list[[-1]]
list[[2 ;; 4]]
{First[list], Last[list], Length[list]}
Rest[list]
10
50
{20, 30, 40}
{10, 50, 5}
{20, 30, 40, 50}
- Positions start at 1; negative positions count from the end.
;;is a span:2 ;; 4means positions 2 to 4.
Changing lists
Append[list, 60]
list
list[[2]] = 99;
list
AppendTo[list, 60];
list
{10, 20, 30, 40, 50, 60}
{10, 20, 30, 40, 50}
{10, 99, 30, 40, 50}
{10, 99, 30, 40, 50, 60}
Append returns a new list and leaves list alone. list[[i]] = v
and AppendTo change the variable itself.
Arithmetic on whole lists
Most math functions are listable — they work element by element:
{1, 2, 3} + 10
{1, 2, 3} * {4, 5, 6}
{1, 2, 3}^2
Sqrt[{1, 4, 9}]
{11, 12, 13}
{4, 10, 18}
{1, 4, 9}
{1, 2, 3}
No loop needed — and it's much faster than a loop.
Nested lists
m = {{1, 2}, {3, 4}};
m[[2]]
m[[2, 1]]
m[[All, 2]]
{3, 4}
3
{2, 4}
All selects every row, so m[[All, 2]] is the second column.
Practice
Make a list of the cubes of 1 to 6, then show its last three elements.
Show solution
cubes = Table[n^3, {n, 6}];
cubes[[-3 ;;]]
{64, 125, 216}
-3 ;; means "from the third-last position to the end".