Skip to content
Math Notes Documentation
Open Math Notes

Lists & sequences

Lists hold several values. Write one with square brackets, index it, slice it, and use mathjs functions to aggregate or transform it. Lists and ranges are capped at 100 items so a runaway sequence cannot freeze the editor. The cap covers everything that builds a list or matrix (ones, zeros, identity, random, concat, kron, …) and assigning past the end of a list (n[500] = 1).

Lists#

Lists are 1-indexed: n[1] is the first element.

[1, 2, 3]
[1, 2, 3]
n = [10, 20, 30]
n[1]
10

Slice with a range:

n = [10, 20, 30, 40]
n[2:4]
[20, 30, 40]

Assign an element:

n = [10, 20, 30]
n[2] = 99
sets the second element

+ and - work element by element, and lists combine with the mathjs functions. The plain *, / and ^ follow matrix rules, so use .*, ./ and .^ to multiply, divide or raise element by element:

[1, 2] + [3, 4]
[4, 6]
[1, 2] .* [3, 4]
[3, 8]
sort([3, 1, 2])
[1, 2, 3]
concat([1, 2], [3, 4])
[1, 2, 3, 4]

Matrices are lists of lists, indexed with two subscripts:

m = [[1, 2], [3, 4]]
m[2, 1]
3

Sequences#

A range start:end makes a list of numbers, with an optional :step.

1:5
[1, 2, 3, 4, 5]
1:2:10
[1, 3, 5, 7, 9]

A range can be named and indexed like any other list:

n = 1:5
n[3]
3

Iteration#

A function receives the whole list or range it is called with. A body such as x * 2 or x + 1 happens to work on every element, but x * x is a dot product (so sq(1:3) is 14). To apply a function to each element, use map.

double = f(x) = x * 2
double(1:5)
[2, 4, 6, 8, 10]
sq = f(x) = x * x
map(1:3, sq)
[1, 4, 9]

Aggregates#

sum, mean, min, max and the rest of the mathjs aggregate functions accept a list or a range.

expenses = [1200, 80, 45]
sum(expenses)
returns 1,325
sum(1:100)
returns 5,050
mean(1:5)
returns 3

sum, total, average and avg also work as bare keywords on the lines above — see Groups & totals.