List iteration
- Kotlin course
- Beginner
- Lesson 62/116
- 5 min
Learn to iterate over lists with for and forEach.
List iteration: for and forEach
The most natural way to walk all elements of a list is the for (x in list) loop. On each pass x is the current element. forEach { } does the same with a lambda.
val cities = listOf("Vienna", "Berlin", "Madrid")
for (city in cities) {
println(city)
}If you also need indexes, you can iterate cities.indices (the range 0..size-1) or walk index-value pairs with cities.withIndex().
forEach, indices and withIndex
forEach takes a lambda and runs it for every element. Inside the lambda the element is known as it. indices returns the index range and withIndex() yields (index, value) pairs.
cities.forEach { println(it) }
for (i in cities.indices) println(i)
for ((i, c) in cities.withIndex()) println("$i: $c")When you need an index, withIndex() is the most readable choice; it gives position and value at once.
Practice Print the cities with a for loop
Create a listOf("Vienna", "Berlin", "Madrid") and use a for (city in cities) loop to print each city on its own line.
Starter code
fun main() {
val cities = listOf("Vienna", "Berlin", "Madrid")
// Print each city on its own line
}Sample solution
fun main() {
val cities = listOf("Vienna", "Berlin", "Madrid")
for (city in cities) {
println(city)
}
}Expected output
Vienna Berlin Madrid
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which one prints each element on its own line?
- for (x in list) println(x) Correct answer
- for (x of list) println(x)
- foreach (x in list) println(x)
- for (x = 0; x < list; x++) println(x)
Explanation: Kotlin's loop form is for (x in list).
2 Fill in the blank: for loop
for (name ____ names) println(name)
for (name in names) println(name)
Explanation: for (name in names) walks and prints each name.
3 Match loop expression to use
| Term | Meaning |
|---|---|
for (x in list) |
Walks each element |
list.forEach { } |
Walks with a lambda |
list.indices |
Range 0..size-1 |
list.withIndex() |
Index+value pairs |
4 What does list.withIndex() return?
- Only indexes
- IndexedValue stream Correct answer
- Only values
- Boolean
Explanation: withIndex() yields IndexedValue pairs; index and value together.