0
0
KotlinHow-ToBeginner · 3 min read

How to Iterate Over List in Kotlin: Simple Examples

In Kotlin, you can iterate over a list using a for loop, the forEach function, or by using indices with for (i in list.indices). These methods let you access each element easily and perform actions on them.
📐

Syntax

Here are common ways to iterate over a list in Kotlin:

  • for (item in list) { ... }: Loops through each element directly.
  • list.forEach { item -> ... }: Uses a lambda to process each element.
  • for (i in list.indices) { val item = list[i]; ... }: Loops using index numbers.
kotlin
val list = listOf("apple", "banana", "cherry")

// Using for loop
for (item in list) {
    println(item)
}

// Using forEach
list.forEach { item ->
    println(item)
}

// Using indices
for (i in list.indices) {
    println("Element at index $i is ${list[i]}")
}
Output
apple banana cherry apple banana cherry Element at index 0 is apple Element at index 1 is banana Element at index 2 is cherry
💻

Example

This example shows how to print each fruit in a list using different iteration methods.

kotlin
fun main() {
    val fruits = listOf("apple", "banana", "cherry")

    println("Using for loop:")
    for (fruit in fruits) {
        println(fruit)
    }

    println("\nUsing forEach:")
    fruits.forEach { fruit ->
        println(fruit)
    }

    println("\nUsing indices:")
    for (index in fruits.indices) {
        println("Fruit at index $index is ${fruits[index]}")
    }
}
Output
Using for loop: apple banana cherry Using forEach: apple banana cherry Using indices: Fruit at index 0 is apple Fruit at index 1 is banana Fruit at index 2 is cherry
⚠️

Common Pitfalls

Some common mistakes when iterating over lists in Kotlin include:

  • Using for (i in list) but expecting i to be an index (it is the element).
  • Modifying the list while iterating, which can cause errors.
  • Using indices without checking if the list is empty, which can cause out-of-bounds errors.
kotlin
val list = listOf("a", "b", "c")

// Wrong: expecting i to be index
for (i in list) {
    println("Index: $i") // i is element, not index
}

// Right: use indices for index
for (i in list.indices) {
    println("Index: $i, Element: ${list[i]}")
}
Output
Index: a Index: b Index: c Index: 0, Element: a Index: 1, Element: b Index: 2, Element: c
📊

Quick Reference

Here is a quick summary of ways to iterate over a list in Kotlin:

MethodDescriptionExample
for loopIterate over elements directlyfor (item in list) { ... }
forEachUse lambda to process each elementlist.forEach { item -> ... }
indicesIterate using index numbersfor (i in list.indices) { val item = list[i] }

Key Takeaways

Use a simple for loop to access each element in a Kotlin list easily.
The forEach function provides a clean way to run code on each list item with a lambda.
Use list.indices when you need the index number along with the element.
Avoid confusing elements with indices to prevent logic errors.
Do not modify a list while iterating to avoid runtime exceptions.