Version: v0.5.1 - Beta.  We welcome contributors & feedback.  THanks!

Lists

A List is a variable that can hold multiple values.

Each item, or element, is separated by a comma.

// A list of strings
let letters = ['a', 'b', 'c'];

// A list of numbers
let evenNumbers = [2, 4, 6, 8, 10];

// Multi-line format
let countries = [
    'Argentina',
    'Brazil',
    'Chile'
];

// Each item can be an expression
let nums = [1 + 9, 2 + 8];

JargonIn other languages, Lists are often called Arrays.

List Elements

You can access elements of a list by the index number of its position.

THT lists use zero-based indexes: the first element is 0, the second element is 1, etc.

let letters = ['a', 'b', 'c', 'd'];

let first = letters[0];  //= 'a'
let second = letters[1]; //= 'b'

// Negative indexes start counting from the end
let last = letters[-1];        //= 'd'
let nextToLast = letters[-2];  //= 'c'

// Modify an index directly
letters[0] = 'x';
print(letters);
//= ['x', 'b', 'c', 'd']

List Methods

Here are some common List methods.

let colors = ['red', 'blue'];

colors.contains('blue');
//= true

colors.length();
//= 2

colors.join(' & ');
//= 'red & blue'

The methods push and pop treat the List as a stack of items. They add and remove the last item in the List.

(Tip: Think of a spring-loaded stack of plates in a cafeteria.)

let colors = ['red', 'blue'];

// Add an item to the end
colors.push('yellow');
//= ['red', 'blue', 'yellow']

// Remove item from the end and return it
colors.pop();  //= 'yellow'
//= ['red', 'blue']

The methods insert and remove let you add and delete items anywhere in the List.

let colors = ['red', 'blue'];

// Add item to the 2nd slot (index: 1)
colors.insert('orange', 1);
//= ['red', 'orange', 'blue']

// Remove item from beginning (index: 0)
colors.remove(0);  //= 'red'

print(colors);
//= ['orange', 'blue']

See Also