How do I add an item to a list in EK9?
← Common Collection Tasks · Ref: Q180
EK9 provides two addition operators: += for mutating the list and + for creating a new list.
MUTATING ADD (+=)
Add an item to the existing list:
numbers += 4
Modifies the list in place.
NEW LIST (+)
Create a new list with the item added:
extended <- numbers + 4
The original list is unchanged.
ADD MULTIPLE ITEMS
Merge another list using :~: or +:
numbers :~: moreNumbers combined <- numbers + moreNumbers
See Q45 for List basics. See Q88 for List operations. See Q186 for merging collections. See Q181 for list remove.
Example
defines module qa.collectiontasks.listadd defines program ListAddDemo() stdout <- Stdout() // === MUTATING ADD (+=) === numbers <- [1, 2, 3] stdout.println(`Before: ${numbers}`) numbers += 4 stdout.println(`After += 4: ${numbers}`) numbers += 5 stdout.println(`After += 5: ${numbers}`) // === NEW LIST (+) === original <- [10, 20] extended <- original + 30 stdout.println(`Original: ${original}`) stdout.println(`Extended: ${extended}`) // === ADD MULTIPLE ITEMS (:~:) === base <- [1, 2, 3] extras <- [4, 5, 6] base :~: extras stdout.println(`After merge: ${base}`) // === ADD MULTIPLE WITH + === left <- [1, 2] right <- [3, 4] combined <- left + right stdout.println(`Combined: ${combined}`) stdout.println(`Left unchanged: ${left}`) // === BUILD FROM EMPTY === built <- List() of String built += "first" built += "second" built += "third" stdout.println(`Built: ${built}`)
Common mistakes
E50060 — EK9 uses the += operator to append items to a list, not an add() method. The operator syntax is consistent across all collection types. See ek9 -h E50060 for details.
Incorrect:
numbers.add(4)
Correct:
numbers += 4
E50060 — EK9 uses the :~: merge operator to add all items from one list to another, not an addAll() method. See ek9 -h E50060 for details.
Incorrect:
base.addAll(extras)
Correct:
base :~: extras
Other ways to ask this
- How do I append an element to a list in EK9?
- What is the EK9 equivalent of list.add()?
- How do I push an item onto a list in EK9?
Coming from another language?
Java: list.add(item), Collections.unmodifiableList for immutable. Python: list.append(item), list.extend(). Rust: vec.push(item). Go: append(slice, item). JavaScript: arr.push(item), [...arr, item] for new array. Kotlin: mutableList.add(item), list + item. EK9: list += item for mutating, list + item for new list.
Keywords: collection, append, mutate, element, insert, plus, task, push, item, list, add