← Back to Kotlin Course | Chapter 8: Collections | Lesson 2 of 7

MutableList

A MutableList is a List you're allowed to keep changing after it's created, adding and removing items whenever you like.

Creating a MutableList

mutableListOf(...) creates a list that supports adding, removing, and replacing elements after creation, unlike the read-only List from listOf().

Example: Creating a MutableList

markup
fun main() {
    val numbers = mutableListOf(1, 2, 3)
    println(numbers)
}

Adding Elements

.add(item) appends a new element to the end of the list, while .add(index, item) inserts it at a specific position, shifting later elements over.

Example: Adding Elements

markup
fun main() {
    val numbers = mutableListOf(1, 2, 3)
    numbers.add(4)
    numbers.add(0, 0)
    println(numbers)
}

Removing Elements

.remove(value) removes the first matching element by value, while .removeAt(index) removes the element at a specific position.

Example: Removing Elements

markup
fun main() {
    val numbers = mutableListOf(10, 20, 30, 40)
    numbers.remove(20)
    numbers.removeAt(0)
    println(numbers)
}

Updating Elements by Index

Assigning to list[index] = value replaces the element at that position directly, without needing to remove and re-add.

Note: Iterating with an index and modifying by index (not structurally) is safe; adding/removing while looping directly is not.

Example: Updating Elements by Index

markup
fun main() {
    val numbers = mutableListOf(1, 2, 3)
    numbers[1] = 99
    println(numbers)
}
Common Mistakes
  1. Using mutableListOf() when a plain read-only listOf() would be safer and clearer for data that never actually needs to change.
  2. Modifying a MutableList while iterating over it directly with a for loop, risking a ConcurrentModificationException.
  3. Forgetting removeAt() takes an index while remove() takes a value, and using the wrong one accidentally.
Chapter Summary
  • mutableListOf(...) creates a MutableList, supporting .add(), .remove(), and .removeAt().
  • .add(item) appends an item to the end; .add(index, item) inserts at a specific position.
  • .remove(item) removes the first occurrence of a value; .removeAt(index) removes by position.
  • Modifying a mutable collection while directly iterating it with a for loop can throw a ConcurrentModificationException.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.