Menu
Coddy logo textTech

List vs MutableList

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 67 of 93.

So far, you've worked with individual variables that hold single values. But what if you need to store a collection of items, like a list of names or a series of numbers? That's where lists come in.

Kotlin provides two types of lists: List and MutableList. The key difference is whether you can modify the list after creating it.

A List is read-only. Its interface does not expose operations to add, remove, or replace elements. It is not a guarantee of deep immutability: the same underlying mutable object could change through another reference:

val fruits = listOf("Apple", "Banana", "Cherry")
val numbers = listOf(1, 2, 3, 4, 5)

A MutableList allows modifications. You can add new elements, remove existing ones, or update values:

val fruits = mutableListOf("Apple", "Banana")
fruits.add("Cherry")  // Now contains: Apple, Banana, Cherry

Use listOf() when your data shouldn't change, and mutableListOf() when you need flexibility. This distinction helps prevent accidental modifications and makes your code's intent clearer.

challenge icon

Challenge

Medium

Create a read-only list called colors containing three strings: "Red", "Green", and "Blue".

Then create a mutable list called numbers starting with two integers: 10 and 20.

Add the value 30 to the numbers list.

Finally, print both lists on separate lines in this order:

  1. The colors list
  2. The numbers list

Try it yourself

fun main() {
    // TODO: Create a read-only list called 'colors' with "Red", "Green", "Blue"
    
    // TODO: Create a mutable list called 'numbers' with 10 and 20
    
    // TODO: Add 30 to the numbers list
    
    // TODO: Print both lists on separate lines (colors first, then numbers)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground