Kotlin List – Iterate over Elements using For Loop
To iterate over elements of a List in Kotlin using for loop, use the following syntax.
</>
Copy
for (element in list) {
//code
}
We get to access ith element of the list during ith iteration of the loop.
Examples
In the following program, we will take a list of integers, and iterate over each of these elements using Kotlin For Loop.
Main.kt
</>
Copy
fun main(args: Array<String>) {
val numbers = listOf(1, 3, 9)
for (number in numbers) {
println(number)
}
}
Output
1
3
9
Now, let us take a list of Strings, and iterate over each of the elements using for loop.
Main.kt
</>
Copy
fun main(args: Array<String>) {
val names = listOf("Abc", "Pqr", "Xyz")
for (name in names) {
println(name)
}
}
Output
Abc
Pqr
Xyz
Conclusion
In this Kotlin Tutorial, we learned how to iterate over elements of a List in Kotlin, using for loop.