Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 06 / Topic 1 of 7

Lists: listOf, mutableListOf, indexing and iteration

A List holds an ordered sequence of values, and listOf(...) is the everyday way to build one. Read it with [index] (0-based, same as every C-family language), its .size, and its .indices.

val weeklyMenu = listOf("Idli", "Dosa", "Poha", "Upma", "Paratha")
println("Weekly menu: $weeklyMenu")
println("Day 1: ${weeklyMenu[0]}")
println("Day 3: ${weeklyMenu[2]}")
println("Valid indices: ${weeklyMenu.indices}")
println("Size: ${weeklyMenu.size}")
Weekly menu: [Idli, Dosa, Poha, Upma, Paratha]
Day 1: Idli
Day 3: Poha
Valid indices: 0..4
Size: 5

listOf(...) gives you a value you can only read — no .add(), no .remove(), nothing that changes it. mutableListOf(...) is the same idea with those operations added back:

val shoppingList = mutableListOf("Rice", "Dal", "Atta")
shoppingList.add("Milk")
shoppingList.add(1, "Sugar")      // insert at a position, shifting everything after it
shoppingList[0] = "Basmati Rice"  // replace by index
shoppingList.remove("Atta")
println("Shopping list: $shoppingList")
Shopping list: [Basmati Rice, Sugar, Dal, Milk]

Real-world example: a day's train stops, a recipe's ingredient order, a playlist — anything where the order itself matters is a List, not a Set.

for (x in list) walks it in that same order; withIndex() pairs each element with its position, so you never manage a counter variable by hand (the same trick Part 4 showed for ranges):

for (item in weeklyMenu) {
    println("Menu item: $item")
}
for ((position, item) in shoppingList.withIndex()) {
    println("${position + 1}. $item")
}
Menu item: Idli
Menu item: Dosa
Menu item: Poha
Menu item: Upma
Menu item: Paratha
1. Basmati Rice
2. Sugar
3. Dal
4. Milk

Full program: examples/01_lists.kt.

Done here? The practice set for Part 6 — including the solutions — is on the part page.

Search the guide