Lists

A list holds any number of values of one type, in order.

nums: [int] = [1, 2, 3, 4, 5]
names: [str] = ["Ada", "Bjarne", "Guido"]
truth: [bool] = []
print(nums)
print(names)
print(truth)

Output:

[1, 2, 3, 4, 5]
["Ada", "Bjarne", "Guido"]
[]

List types

The type of a list is its element type in square brackets:

TypeA list of
[int]ints
[float]floats
[byte]bytes
[bool]bools
[str]strings
[[int]]lists of ints
[[[str]]]lists of lists of strings

All elements must have the list’s type. Number literals adapt as usual: [1, 2] can be a [float].

An empty list [] gets its type from where it is used, so it must be declared first: print([]) is an error.

Reading an element

Elements are numbered from 0. list[i] reads element i:

names: [str] = ["Ada", "Bjarne", "Guido"]
print(names[0])
print(names[2])

Output:

Ada
Guido

The index must be an int between 0 and len(list) - 1. Any other index, including a negative one, stops the program:

nums: [int] = [1, 2, 3]
print(nums[3])

Output:

example.luma:2:11: runtime error: index 3 out of range (length 3)

Changing an element

nums: [int] = [1, 2, 3]
nums[0] = 10
print(nums)

Output:

[10, 2, 3]

Adding an element

list[] = value adds the value to the end of the list:

nums: [int] = [1, 2]
nums[] = 3
nums[] = 4
print(nums)

Output:

[1, 2, 3, 4]

Removing an element

remove(list, i) removes element i. The elements after it move forward, so their indexes become one smaller:

names: [str] = ["Ada", "Bjarne", "Guido"]
remove(names, 0)
print(names)
print(names[0])

Output:

["Bjarne", "Guido"]
Bjarne

Length

len(list) gives the number of elements:

nums: [int] = [1, 2, 3]
print(len(nums))
print(nums[len(nums) - 1])

Output:

3
3

Lists of lists

A list can hold other lists, to any depth:

grid: [[int]] = [[1, 2], [3], []]
grid[2][] = 9          // add to the third inner list
grid[] = [7, 8]        // add a new inner list
print(grid)
print(grid[0][1])
print(len(grid))

Output:

[[1, 2], [3], [9], [7, 8]]
2
4

Assignment shares the list

Assigning a list to another variable doesn’t copy it: both names refer to the same list. A change made through one name is visible through the other:

a: [int] = [1, 2]
b: [int] = a
b[] = 3
print(a)

Output:

[1, 2, 3]

This works the same way as in Python, JavaScript and Java. It also applies to inner lists: row: [int] = grid[0] gives a name to the inner list, and changes through row change grid.

Printing

print shows a list in square brackets, with elements separated by , . Strings inside a list are shown in double quotes, so ["a, b"] and ["a", "b"] look different:

print(["a, b"])
words: [str] = ["a", "b"]
print(words)
print([1.5, 2.0])

Output:

["a, b"]
["a", "b"]
[1.5, 2.0]

A part of a list

nums.part(start, end) gives a new list of the elements from position start up to end, without end, as part does for a str:

a: [int] = [3, 4, 5, 6, 7, 8, 9]
print(a.part(0, 3))
print(a.part(5, len(a)))
a.part(1, 3).walk(n) {
    print(n)
}

Output:

[3, 4, 5]
[8, 9]
4
5

The part is a new list: changing it doesn’t change the first one. A part that doesn’t fit the list raises error 2: part(2, 9) is out of range (length 7).

Sorting, searching and more

MethodGives
nums.sum(), nums.min(), nums.max()the sum, the smallest, the largest (lists of ints and floats)
nums.mean()the average, a float
nums.has(x)whether x is in the list
nums.index(x)the position of the first x, or -1
nums.sort()a new list, sorted
people.sort(byAge)a new list, in the order a function says (below)
nums.reverse()a new list, back to front
nums.unique()a new list without duplicates (the first of each stays)
a.union(b)a new list of the elements in a or b
a.intersect(b)a new list of the elements in both
a.diff(b)a new list of the elements in a but not in b
a: [int] = [3, 1, 3, 2]
print(a.sort())
print(a.reverse())
print(a.unique())
print("${a.has(2)} ${a.index(3)} ${a.index(9)}")
print(a.union([2, 5]))
print(a.intersect([2, 3]))
print(a.diff([1]))
print(a)

Output:

[1, 2, 3, 3]
[2, 3, 1, 3]
[3, 1, 2]
true 0 -1
[3, 1, 2, 5]
[3, 2]
[3, 2]
[3, 1, 3, 2]
  • They never change the list itself: a above is the same at the end. To keep a sorted list, assign it: a = a.sort().
  • union, intersect, diff and unique give each element once, in the order they first appear (a’s, then b’s), as sets do.
  • sort puts numbers from small to large, and strs by their characters’ numbers (code points): "Apple" before "apple", "z" before "ä". Equal elements keep their order.
  • Which lists have them: has and index lists of numbers, bools and strs; sort() lists of numbers and strs, sort(function) every list; unique, union, intersect and diff lists of ints, bytes, bools and strs (the elements a set can have); reverse every list.

Sorting by a function

To sort objects, or to sort in another order, give sort a function that takes two elements and says whether the first comes before the second:

obj Person {
    name: str = ""
    age: int = 0
}

fn byAge(a: Person, b: Person): bool {
    return a.age < b.age
}

fn oldestFirst(a: Person, b: Person): bool {
    return a.age > b.age
}

people: [Person] = [Person{name: "Mari", age: 41}, Person{name: "Jaan", age: 29}, Person{name: "Anu", age: 29}]
people.sort(byAge).walk(p) {
    print("${p.name} ${p.age}")
}
print(people.sort(oldestFirst)[0].name)

Output:

Jaan 29
Anu 29
Mari 41
Mari
  • Equal elements keep their order: Jaan stays before Anu. So one sort can order by several things; check the first, and only when it’s equal the next:

    obj Name {
        first: str = ""
        last: str = ""
    }
    
    fn byName(a: Name, b: Name): bool {
        if a.last != b.last {
            return a.last < b.last
        }
        return a.first < b.first
    }
  • The function must be fn(T, T): bool for a list of T. It works on every list, numbers and strs too: nums.sort(down) with fn down(a: int, b: int): bool { return a > b }.

  • An error the function raises comes from the line of the sort.

  • A lambda can say it on the spot: people.sort(fn(a, b) => a.age < b.age).

Sum, smallest, largest, average

scores: [int] = [70, 85, 92, 64]
print(scores.sum())
print(scores.min())
print(scores.max())
print(scores.mean())
prices: [float] = [2.5, 4.0, 1.25]
print(prices.sum())

Output:

311
64
92
77.75
7.75
  • They work on [int] and [float]. sum, min and max give the list’s type; mean a float.
  • The sum of an empty list is 0; min, max and mean of an empty list raise error 2: mean of an empty list.

Map and filter

map gives a new list of what a function gives for each element; filter a new list of the elements a function says yes to. The list itself stays as it is.

nums: [int] = [1, 2, 3, 4, 5, 6]
print(nums.map(fn(n) => n * n))
print(nums.filter(fn(n) => n > 3))
labels: [str] = nums.filter(fn(n) => n % 2 == 0).map(fn(n) => "#${n}")
print(labels)

Output:

[1, 4, 9, 16, 25, 36]
[4, 5, 6]
["#2", "#4", "#6"]
  • map takes fn(T): R for a list of T and gives a [R]: the new elements can be of another type. filter takes fn(T): bool and gives a [T].
  • Any function value works, a named one too: words.map(shout).
  • An error the function raises comes from the line of the map or filter.

Going through all elements

nums.walk(n) { ... } runs a block for each element; nums.walk(i, n) { ... } also gives each one’s position. See Walk loops.

Not available yet

  • Lists can’t be compared with == or !=.

See Limitations.