beginner first-steps

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.

Part of: Install and setup

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
yellow

list<string> means this list can only hold strings. Use list<integer> for whole numbers, list<number> for decimals.

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
true

colors[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.

  • Declare with list<type> — for example list<string> or list<integer>
  • 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
📚 → Book 1, Chapter 12 : Writing Your Own Functions →
Copied!