Lists: Keeping Groups of Things
What if you need to store not just one value, but a whole collection of them? A list of names, a set of scores, a shopping cart? That's exactly what list is for.
start:
list<string> colors = ["red", "green", "blue"]
print(colors.length().toString())
print(colors[0])
colors.add("yellow")
print(colors.length().toString())
iterate color in colors
print(color)3
red
4
red
green
blue
yellowlist
You can also start with an empty list and build it up:
start:
list<integer> scores
scores.add(85)
scores.add(92)
scores.add(78)
print("Total scores: {scores.length()}")
print(scores.contains(92).toString())Total scores: 3
truecolors[0] gives you the first item — lists start counting at zero, not one. First item is always at position 0, second at 1, and so on.
Quick recap
- Declare with list
— for example list or list - Add items with .add(value)
- Access by position with list[0] — first item is index 0
- .length() returns how many items are in the list
- .contains(value) checks if something is in the list
- Use iterate item in list to loop through everything