Lists

// a list holds values of one type
primes = [2, 3, 5]
print(primes, primes.len())

// indexes start at 0, and negative ones count from the end
print(primes[0], primes[-1])
primes[0] = 1
print(primes)

// append adds to the end
primes.append(7)
print(primes)

// for walks a list in order
total = 0
for p in primes;
    total = total + p
print(total)

// lists are shared, not copied
alias = primes
alias.append(11)
print(primes)

// lists can nest
grid = [[1, 2], [3, 4]]
grid[1][0] = 30
print(grid, grid[1][0])

prints

[2, 3, 5] 3
2 5
[1, 3, 5]
[1, 3, 5, 7]
16
[1, 3, 5, 7, 11]
[[1, 2], [30, 4]] 30

Working with lists

A list holds values of a single type, written list[int], list[str], list[list[float]], and so on. An empty list [] gets its type from what is later appended to it or assigned from it.

  • items[i] reads an element, counting from 0. A negative index counts from the end, so items[-1] is the last element.

  • items[i] = value replaces an element.

  • items.append(value) adds to the end, and items.len() counts the elements.

  • for item in items; walks the list in order. If the body appends to the list, the loop also visits the new elements.

An index past either end stops the program with list index out of range.

Lists are shared, not copied: assigning a list to another variable, or passing it to a function, gives a second name for the same list, so changes through one name show through the other.

Putting it together

This program finds primes with the sieve of Eratosthenes, using a list[bool] of candidates:

// prints the primes below a limit with the sieve of Eratosthenes
def primes_below(limit);
    is_prime = []
    for i in range(limit);
        is_prime.append(i >= 2)
    found = []
    for n in range(2, limit);
        if is_prime[n];
            found.append(n)
            multiple = n * n
            while multiple < limit;
                is_prime[multiple] = false
                multiple = multiple + n
    ret found

primes = primes_below(50)
print(primes)
print(primes.len(), "primes below 50")

prints

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
15 primes below 50

Next, Input.