Menu
Coddy logo textTech

Modifying Lists

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

With MutableList, you can change your list after creating it. Let's explore the core operations for modifying list contents.

To add elements, use add(). You can append to the end or insert at a specific index:

val tasks = mutableListOf("Email", "Meeting")
tasks.add("Report")           // Adds at the end
tasks.add(1, "Call")          // Inserts at index 1
// Result: [Email, Call, Meeting, Report]

To remove elements, use remove() to delete by value, or removeAt() to delete by index:

val items = mutableListOf("A", "B", "C", "D")
items.remove("B")      // Removes "B"
items.removeAt(0)      // Removes element at index 0
// Result: [C, D]

To update an existing element, assign a new value using its index:

val colors = mutableListOf("Red", "Green", "Blue")
colors[1] = "Yellow"
// Result: [Red, Yellow, Blue]

Remember, these operations only work with MutableList. Attempting them on a regular List will cause a compilation error.

challenge icon

Challenge

Medium

Create a mutable list called playlist with three songs: "Song A", "Song B", and "Song C".

Perform the following modifications in order:

  1. Add "Song D" to the end of the list
  2. Insert "Song X" at index 1
  3. Remove "Song B" from the list (by value)
  4. Update the element at index 0 to "New Song A"

Print the final list.

Try it yourself

fun main() {
    // TODO: Create a mutable list called playlist with "Song A", "Song B", and "Song C"
    
    // TODO: Add "Song D" to the end of the list
    
    // TODO: Insert "Song X" at index 1
    
    // TODO: Remove "Song B" from the list (by value)
    
    // TODO: Update the element at index 0 to "New Song A"
    
    // Print the final list
    // println(playlist)
}
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