Beginner 7 min readKotlin 2.0
Kotlin For Loop — Iterating with Ranges and Collections
Kotlin's for loop iterates over any iterable — ranges, lists, maps, and strings. It is concise and removes the need for a counter variable.
What You Will Learn
- Loop over a range with ..
- Use downTo and step
- Iterate over a list and map
- Use withIndex for index + value
- Loop over a String
Looping Over a Range
Use 1..5 to create an inclusive range and iterate over it.
Basic For Loop
kotlin
fun main() {
for (i in 1..5) {
print("$i ")
}
println()
for (i in 1 until 5) {
print("$i ")
}
}Output
1 2 3 4 5
1 2 3 4
1..5 includes both endpoints: 1, 2, 3, 4, 5. 1 until 5 excludes the end: 1, 2, 3, 4.
Beginner Tip: Use until when you want to loop n times starting from 0: for (i in 0 until n)
downTo and step
Count down with downTo. Skip values with step.
downTo and step
kotlin
fun main() {
for (i in 5 downTo 1) print("$i ")
println()
for (i in 0..10 step 2) print("$i ")
}Output
5 4 3 2 1
0 2 4 6 8 10
downTo counts backward. step n skips every n values. Both can be combined: 10 downTo 0 step 2.
Iterating Collections
Iterate directly over lists, sets, maps, and strings.
Iterating a List and Map
kotlin
fun main() {
val fruits = listOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {
println(fruit)
}
val capitals = mapOf("India" to "Delhi", "France" to "Paris")
for ((country, capital) in capitals) {
println("$country: $capital")
}
}Output
Apple
Banana
Cherry
India: Delhi
France: Paris
for...in works on any Iterable. Map destructuring (country, capital) unpacks each entry automatically.
withIndex
Get both the index and value using withIndex().
withIndex
kotlin
fun main() {
val items = listOf("Kotlin", "Java", "Python")
for ((index, value) in items.withIndex()) {
println("$index: $value")
}
}Output
0: Kotlin
1: Java
2: Python
withIndex() returns pairs of (index, value). Destructuring in the for loop unpacks each pair.
Practice Exercise
Exercisepredict output
What prints? for (i in 1..4) print("$i ")
Quick Quiz
Quick Quiz
What does 1 until 5 produce?
Frequently Asked Questions
Related Tutorials
Last updated: 2026-05-01Kotlin 2.0
Written by KotlinGuide Editorial Team · Reviewed by KotlinGuide Technical Review