List
Lists are mutable in Andy C++.
let my_list = [1,2,3];
// Values inside a list can be changed
my_list[2] = 4;
// You can add elements to the end of a list
my_list.push(99);
// Remove and return the last element of the list
let element = my_list.pop();
Indexing
Lists, strings, and tuples also support negative indexes. Negative indexes count from the end.
let my_list = [1,2,3,4,5,6,7,8,9];
assert_eq(9, my_list[-1]);
Element accessors
Besides the [] operator, lists provide four element accessor functions. They
differ on two axes: whether negative indexes are allowed, and what happens when
the index is out of bounds.
| function | index | out of bounds |
|---|---|---|
get | non-negative only (negative is an error) | error |
get? | non-negative only (negative is an error) | None |
index | signed; negatives wrap from the end | error |
index? | signed; negatives wrap from the end | None |
let my_list = [10, 20, 30];
assert_eq(my_list.get(0), 10);
assert_eq(my_list.get?(9), None); // in range for a usize, past the end
assert_eq(my_list.index(-1), 30); // wraps like `[]`
assert_eq(my_list.index?(-9), None);
index behaves like the [] operator (wrap + error on out of bounds);
index? is its non-throwing counterpart.
Slicing
Use ranges to slice lists. Ranges can be inclusive or exclusive. Negative indices count from the end of the list.
let my_list = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
// Exclusive range: 3 to 6 (does not include index 6)
assert_eq([30, 40, 50], my_list[3..6]);
// Inclusive range: 3 to 6 (includes index 6)
assert_eq([30, 40, 50, 60], my_list[3..=6]);
// Negative indices: Counting from the end of the list
assert_eq([80, 90], my_list[-3..-1]);
A range whose start lands after its end (for example my_list[6..3]) is out of
bounds and raises an error rather than returning a reversed or empty slice. This
holds for lists, strings, tuples and deques alike.
Operators
| Operator | Function |
|---|---|
++ | Concatenation |
<> | Coerce operands into strings and concatenate |
in | Checks if an element is present in the list |
not in | Checks if an element is not present in the list |
== | Equality |
!= | Inequality |
> | Greater (lexicographically) |
< | Less (lexicographically) |
>= | Greater equals (lexicographically) |
<= | Less equals (lexicographically) |