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)
// in looks for an element
print(5 in primes, 4 in primes, 4 not in primes)
// for walks a list in order
total = 0
for p in primes:
total += p
print(total)
// assigning a list copies it, so changing the copy leaves the original alone
alias = primes
alias.append(11)
print(primes, alias)
// 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]
true false true
16
[1, 3, 5, 7] [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 from0. A negative index counts from the end, soitems[-1]is the last element.items[i] = valuereplaces an element.items.append(value)adds to the end, anditems.len()counts the elements.appendreturns nothing, so it is always a statement of its own.items.pop()removes the last element and returns it as an option, which isnoneif the list is empty, anditems.pop(i)removes and returns the one ati.items.insert(i, value)putsvalueati,items.extend(more)adds every element ofmoreto the end, anditems.sort()puts the list in ascending order, for numbers, strings, and any other type that can be ordered with<.items[start:stop]is a new list of part ofitems, as in Python.value in itemstests whether some element equalsvalue, andvalue not in itemswhether none does.inworks on Maps (their keys) and strings (their text) too.for item in items:walks the list in order, as it was when the loop started. If the body appends to the list, the loop does not visit the new elements.
An index past either end stops the program with an error such as
list index out of range (index 5, length 1).
Slices, more methods, and arithmetic¶
// slices copy part of a list
xs = [10, 20, 30, 40, 50]
print(xs[1:3], xs[:2], xs[-2:], xs[::-1], xs[::2])
// pop removes and returns an element (without an index, as an option, since the list may be
// empty), insert adds one anywhere, extend adds a whole list
last = xs.pop()
first = xs.pop(0)
xs.insert(1, 25)
xs.extend([60, 70])
print(last, first, xs)
// arithmetic works element by element, and a number applies to every element
prices = [2.5, 4.0, 10.0]
counts = [4.0, 2.0, 1.0]
totals = prices * counts
print(totals, totals * 1.08, -counts)
// and inside functions
fn scale(values: list[float], factor: float) -> list[float]:
ret values * factor + 1.0
print(scale(prices, 2.0))
prints
[20, 30] [10, 20] [40, 50] [50, 40, 30, 20, 10] [10, 30, 50]
some(50) 10 [20, 25, 30, 40, 60, 70]
[10.0, 8.0, 10.0] [10.8, 8.64, 10.8] [-4.0, -2.0, -1.0]
[6.0, 9.0, 21.0]
A slice xs[start:stop:step] works as in Python: any part can be left out, negative bounds
count from the end, and bounds past the end are clamped. It is a new list, so changing it never
changes xs.
Arithmetic on lists of ints or floats works element by element, like numpy’s arrays, so
prices * counts multiplies matching elements and totals * 1.08 multiplies each one. Both
lists must have the same length. This is the one place lists behave differently from Python,
where + joins lists and * repeats them: use extend to join lists. stone compiles each such
expression to a single loop with no intermediate lists, computing two elements at a time where
it can, so it can outrun the same numpy code, which builds a temporary array for each operator. See syntax
for the details.
Lists are values¶
A list is a value, like a number: assigning it to another variable, passing it to a function, or putting it in another list gives a copy, so a change through one name never shows through another. This is where stone differs from Python, which shares the list instead.
a = [1, 2]
b = a
b.append(3)
print(a, b) // [1, 2] [1, 2, 3]
A function that changes a list it was given changes its own copy, so it returns the list, and the caller assigns the result:
fn with_total(xs: list[int]) -> list[int]:
total = 0
for x in xs:
total += x
xs.append(total)
ret xs
scores = [3, 4]
scores = with_total(scores)
print(scores) // [3, 4, 7]
For the same reason, a function can read a global list but not change it; it takes the list as an argument and returns the new one instead. The checker points out each of these.
The copies cost nothing until they are needed. Copies share their elements, and a list is only
copied when it is about to change while another variable still holds it, so changing a list
that only one variable holds happens in place. That includes scores = with_total(scores)
above: since scores is replaced by the result, stone hands the list itself to the function,
which appends to it in place. The same goes for any list at its last use, such as xs in
ys = xs when nothing reads xs afterward. See
value semantics for why stone works this way.
Tuples¶
A tuple groups a few values of different types, such as a name and a score:
// a tuple holds a few values of different types
point = (3, 4)
person = ("ann", 31, ["chess", "go"])
print(point, person, person[0], person[-1][1])
// a function returns several values as a tuple
fn min_max(xs: list[int]) -> tuple[int, int]:
low = xs[0]
high = xs[0]
for x in xs:
if x < low:
low = x
if x > high:
high = x
ret (low, high)
low, high = min_max([4, 9, 1, 7])
print(low, high)
// names separated by commas unpack a tuple, and a swap needs no temporary
a = "left"
b = "right"
a, b = (b, a)
print(a, b)
// a list of tuples unpacks one element at a time
scores = [("ann", 3), ("bo", 5)]
scores.append(("cy", 4))
for name, score in scores:
print(name, score)
print(scores, scores[1][0])
prints
(3, 4) ('ann', 31, ['chess', 'go']) ann go
1 9
right left
ann 3
bo 5
cy 4
[('ann', 3), ('bo', 5), ('cy', 4)] bo
A tuple’s type lists the type of each value, as in tuple[str, int], and a function that
returns one, like min_max above, gives back several values at once. Names separated by
commas unpack a tuple into variables, after = or for, and t[0] or t[-1] reads one
value. A tuple never changes: to change a value, build a new tuple. A tuple’s values always
need their parentheses, so x = 1, 2 is an error that suggests x = (1, 2). See
Types for the details.
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
fn primes_below(limit: int) -> list[int]:
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, Maps.