List Operations — Clean Language
← All tutorials
language-deep-dive6 min

List Operations

Lists are Clean Language's sequence type. They grow dynamically, hold elements of one type, and have a predictable set of operations. Once you know the list pattern — add, access, iterate — you can handle any collection.

Create, add, access, and measure a list:

start:\n    list<string> fruits = []\n    fruits.add("apple")\n    fruits.add("banana")\n    fruits.add("cherry")\n\n    print("Count: " + fruits.length().toString())\n    print("First: " + fruits[0])\n    print("Last: " + fruits[fruits.length() - 1])\n    print("Has banana: " + fruits.contains("banana").toString())\n    print("Has grape: " + fruits.contains("grape").toString())
Count: 3\nFirst: apple\nLast: cherry\nHas banana: true\nHas grape: false

Start with an empty list [] and specify the element type in the declaration. .add() appends to the end. Index access [n] gets a specific element (starting at 0). .length() returns the count. .contains() returns a boolean — use it directly in if conditions.

Build lists dynamically and search through them:

start:\n    list<integer> squares = []\n    iterate n in 1 to 8\n        squares.add(n * n)\n\n    string target = "36"\n    integer found_at = -1\n    iterate i in 0 to squares.length() - 1\n        if squares[i].toString() == target\n            found_at = i\n\n    if found_at >= 0\n        print(target + " found at index " + found_at.toString())\n    else\n        print(target + " not found")
36 found at index 5

Build a list dynamically by calling .add() inside an iterate. Search it by iterating with an index, checking each element, and recording the position. This count-then-iterate pattern works for any list of any size.

Quick recap

  • Declare as list where T is the element type: list, list
  • .add(value) appends to the end of the list
  • [n] accesses element at index n — first is [0], last is [.length() - 1]
  • .contains(value) returns boolean — safe to use directly in if conditions
Copied!