# Lists

If you need to do calculations on a collection of related values, a list is a convenient way to group them together. To create a list, surround your values with `[` and `]` and separate them with a comma:

``````[2, 5, 23]
[\$8 for breakfast, \$12 for lunch, \$28 for dinner]``````
``````[2, 5, 23]
[\$8, \$12, \$28]``````

Any kind of value can be kept in a list, including other lists. They don't have to be the same kind:

``````[]  // Empty list
[42, true, pi]
[tan(0), 5 meters as feet, 5/2 == 2.5]
[2 + 1, [3 + 2], 4 + 3]``````
``````[]
[42, true, 3.14]
[0, 16.4 ft, true]
[3, , 7]``````

## Working with Lists

Lists can be included in all basic arithmetic. For operations using two values (like add or multiply), the other value must either be single or a list of the same length.

``````[1, 2, 3] + 3
[2, 4, 6] + 10%
[1, 2, 3] × [2, 3, 4]
[1, 2, 3] - [1, 2]  // Different lengths``````
``````[4, 5, 6]
[2.2, 4.4, 6.6]
[2, 6, 12]
●``````

Lists can also be compared to each other, but they must have the same number of elements.

``````[1, 2, 3] == [1, 200%, 9/3]
[2, 3, 4] > [1, 2, 3]
[1, 3, 5] <= [2, 3]``````
``````true
true
●``````

The elements of a list can have their elements converted just like a number.

``````[2, 3km, 4] as meters
[1, 2, 3] as binary``````
``````[2 m, 3,000 m, 4 m]
[1₂, 10₂, 11₂]``````

There are also a number of sequence functions that let you operate on lists. Many of these are higher-order functions where you supply another function that is applied to all the elements of the list. Here's a few basic examples. See the documentation for each function to get a full explanation of how they work.

``````count([1, 3, 5])
filter([1, 2, 3, 4, 5], is even)
map([-2, -1, 1, 2], abs)``````
``````3
[2, 4]
[2, 1, 1, 2]``````

## Accessing Elements

To fetch a value out of a list, you ask for it by its position in the list starting with 1. Put the position you want inside `[` and `]`:

``````list = [2, 4, 6, 8]
list
list``````
``````[2, 4, 6, 8]
2
6``````

You can also ask for values starting at the end by using negative numbers:

``````list = [2, 4, 6, 8]
list[-1]
list[-3]``````
``````[2, 4, 6, 8]
8
4``````

If you need a portion of a list, use a range instead of a number:

``````list = [2, 4, 6, 8]
list[1..3]
list[3..4]
list[1..4 step 2]``````
``````[2, 4, 6, 8]
[2, 4, 6]
[6, 8]
[2, 6]``````

In addition to retrieving values, subscripts can be used to assign new values:

``````list = [2, 4, 6, 8]
list = 42
list[3..4] = 23
list``````
``````[2, 4, 6, 8]
42
23
[2, 42, 23, 23]``````

To dive into nested lists, list the positions of each list element starting with the outer list. You can put each position in its own subscript like `list` or group them in a single subscript like `list[1, 3]`:

``````nested = [[1, 2, 3], [4, 5, 6]]
nested
nested[2, 1]
nested``````
``````[[1, 2, 3], [4, 5, 6]]
[4, 5, 6]
4
4``````

Didn't find what you were looking for?