Use withIndex() and destructure the pair: for ((i, item) in list.withIndex()) { … }. In a lambda chain, list.forEachIndexed { i, item -> … } does the same. When you only need the positions, loop over list.indices. To count, write for (i in 0 until n) (or 0..<n); to count backwards, write for (i in n downTo 0), because n..0 is an empty range.
Kotlin's for loop walks over anything with an iterator, and it has no three-part for (int i = 0; i < n; i++) form. You get an index in one of three ways: pair each element with its position (withIndex(), forEachIndexed), loop over the positions themselves (indices, 0 until size), or let a collection function hand you the index while it builds a result (mapIndexed, filterIndexed). The sections below cover each, then counting loops with step, counting backwards with downTo and reversed(), and a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1withIndex() in a for loopRecommended
withIndex() wraps each element in an IndexedValue holding index and value, and the parentheses in for ((i, item) in …) unpack it into two variables. It is the closest thing to Python's enumerate, and because it is a plain for loop, break and continue work as usual. It doesn't copy the list. Lists, arrays, strings, sets and sequences all have it, and the index always starts at 0, so add 1 when you number things for people.
fun main() { val fruits = listOf("apple", "banana", "cherry") // withIndex() pairs each element with its position for ((index, fruit) in fruits.withIndex()) { println("$index: $fruit") } // Start counting at 1 for people: add 1 when you print for ((i, fruit) in fruits.withIndex()) { println("${i + 1}. $fruit") } // break and continue work as in any for loop for ((i, fruit) in fruits.withIndex()) { if (i == 0) continue if (fruit.startsWith("c")) break println("skipped the first, stopped before c: $fruit") } // Each item is an IndexedValue with .index and .value val first = fruits.withIndex().first() println(first) println("${first.index} ${first.value}") // Strings, arrays and sequences have withIndex() too for ((i, c) in "Kot".withIndex()) { println("char $i = $c") } }
Output
The first loop prints 0: apple to 2: cherry, the second 1. apple to 3. cherry. The third loop skips index 0 with continue and stops at cherry with break, so only banana prints. Printing one item directly shows the wrapper, IndexedValue(index=0, value=apple); the destructuring in the loop header is what saves you from writing .index and .value. On a string, each value is a Char.
2forEachIndexed
forEachIndexed is the lambda version: it calls your block with the index first and the element second. It reads well at the end of a call chain. Because the body is a lambda, not a loop, break and continue don't apply to it: return@forEachIndexed skips to the next element, and there is no way to stop early, so use a withIndex() loop when you need to (see how to break out of loops). A Map has no positions of its own; number its entries the same way, in the map's order.
fun main() { val colors = listOf("red", "green", "blue", "gray") // forEachIndexed: the index comes first, then the element colors.forEachIndexed { i, color -> println("$i -> $color") } // return@forEachIndexed skips to the next element, like continue colors.forEachIndexed { i, color -> if (color.startsWith("g")) return@forEachIndexed println("not green or gray: $i $color") } // Name a parameter you do not need _ val labels = mutableListOf<String>() colors.forEachIndexed { i, _ -> labels += "item$i" } println(labels) // A Map has no index: number its entries val stock = mapOf("pens" to 12, "pads" to 4) stock.entries.forEachIndexed { i, (name, count) -> println("#$i $name=$count") } }
Output
The second block skips green and gray and prints only 0 red and 2 blue: the index still counts every element, skipped or not. _ marks the element as unused. For the map, the parentheses in (name, count) unpack each entry, giving #0 pens=12 and #1 pads=4 in insertion order. A break inside forEachIndexed, with no loop around it, fails to compile with 'break' and 'continue' are only allowed inside loops.
3indices and lastIndex
When you need the position more than the element, loop over list.indices, the range from 0 to list.lastIndex. This is the form for writing back into a MutableList or an array, comparing an element with its neighbor, or walking two lists side by side. It replaces the Java for (int i = 0; i < list.size(); i++), and unlike 0..list.size - 1 it can't be off by one. For two lists, names.zip(scores) also pairs them without any index.
fun main() { val scores = mutableListOf(70, 85, 90, 65) // indices is the range 0..lastIndex println(scores.indices) println(scores.lastIndex) // Loop over the positions when you need to write back for (i in scores.indices) { scores[i] += 5 } println(scores) // Compare each element with the one before it for (i in 1..scores.lastIndex) { val change = scores[i] - scores[i - 1] println("$i: ${scores[i - 1]} -> ${scores[i]} ($change)") } // An empty list: indices is empty, lastIndex is -1 val empty = emptyList<Int>() println("${empty.indices} ${empty.lastIndex}") for (i in empty.indices) println("never printed") // Two lists of the same length, by position val names = listOf("Ann", "Bo", "Cy", "Di") for (i in names.indices) { println("${names[i]} scored ${scores[i]}") } }
Output
For four scores, indices prints as 0..3 and lastIndex is 3. Writing through the index adds 5 to each score in place: [75, 90, 95, 70]. Starting the second loop at 1 lets it read scores[i - 1] safely. On an empty list, indices is 0..-1, a range with nothing in it, so the loop body never runs and lastIndex is -1. Don't remove elements while looping forward over indices: the range is fixed when the loop starts, so the later elements shift and the loop runs past the end (section 5 shows the safe way).
4Counting loops: .., until, ..< and step
For a loop that just counts, put a range after in. 1..n includes both ends. 0 until n and 0..<n stop before n; they mean the same thing, and ..< is the newer spelling (stable since Kotlin 1.9), so use until on older projects. step sets the stride, and repeat(n) runs a block n times when you hardly need the counter. The loop variable is a val: i += 2 inside the body fails with 'val' cannot be reassigned., so use step, or a while loop when the stride changes.
fun main() { val n = 5 // .. includes both ends: 1, 2, 3, 4, 5 for (i in 1..n) print("$i ") println("(1..n)") // until and ..< stop before the end: 0, 1, 2, 3, 4 for (i in 0 until n) print("$i ") println("(0 until n)") for (i in 0..<n) print("$i ") println("(0..<n)") // step skips: every second number, every third number for (i in 0..10 step 2) print("$i ") println("(step 2)") for (i in 1..10 step 3) print("$i ") println("(step 3)") // repeat(n) when you only need the count repeat(2) { i -> println("attempt ${i + 1}") } // A range is a value you can print, check and count val r = 0..<n println("$r ${3 in r} ${r.count()} ${(0..10 step 4).toList()}") }
Output
1..n gives 1 2 3 4 5, while both 0 until n and 0..<n give 0 1 2 3 4. 0..10 step 2 reaches 10 because 10 is on the stride; 1..10 step 3 also ends exactly on 10, but a stride that misses the end just stops before it, as (0..10 step 4) giving [0, 4, 8] shows. A range prints in its closed form, so 0..<5 shows as 0..4. A for loop can count over Int, Long and Char ranges ('a'..'e'), but not over Double.
5Counting backwards: downTo and reversed()
A range written high to low, such as 5..1, is empty: Kotlin doesn't guess the direction, and the loop silently does nothing. Count down with 5 downTo 1, which includes both ends and takes a step too. To flip a range you already have, or a list's positions, call reversed(). Walking backwards is also the safe way to remove elements by index, because removing one only shifts the elements you have already visited.
fun main() { // downTo counts backwards, both ends included for (i in 5 downTo 1) print("$i ") println("(5 downTo 1)") // downTo with step: every second number for (i in 10 downTo 0 step 2) print("$i ") println("(10 downTo 0 step 2)") // reversed() flips any range or list for (i in (0..<4).reversed()) print("$i ") println("(reversed)") // Backwards through a list, keeping the real index val steps = listOf("wake", "wash", "dress") for (i in steps.indices.reversed()) { println("$i ${steps[i]}") } // Removing by index is safe from the end val nums = mutableListOf(1, 2, 3, 4, 5, 6) for (i in nums.lastIndex downTo 0) { if (nums[i] % 2 == 0) nums.removeAt(i) } println(nums) // Trap 1: 5..1 is empty, so this loop never runs for (i in 5..1) println("never printed") println("5..1 has ${(5..1).count()} elements") // Trap 2: a reversed stepped range starts at its last element println((0..10 step 3).toList()) println((0..10 step 3).reversed().toList()) }
Output
5 downTo 1 gives 5 4 3 2 1 and 10 downTo 0 step 2 gives 10 8 6 4 2 0. The step stays positive even when counting down: 10 downTo 0 step -2 throws IllegalArgumentException with Step must be positive, was: -2. Removing the even numbers from the end leaves [1, 3, 5]. Doing the same forward over indices on [1, 2, 4, 5, 6] skips the 4 that slides into the freed slot and then fails with Index 4 out of bounds for length 3. The last two lines show that reversing 0..10 step 3 starts at 9, its real last element, not at 10.
6mapIndexed, filterIndexed and friends
When the loop exists to build a new list, the collection functions have indexed versions that take (index, element): mapIndexed, filterIndexed, foldIndexed, mapIndexedNotNull and more. To filter on the value but keep the original index, go through withIndex(). And when the loop exists only to find a position, indexOfFirst and indexOfLast do it in one call and return -1 when nothing matches.
fun main() { val words = listOf("kotlin", "java", "scala", "groovy", "clojure") // mapIndexed: build a new list from index and element val numbered = words.mapIndexed { i, w -> "${i + 1}:$w" } println(numbered) // filterIndexed: keep elements by position val evenPositions = words.filterIndexed { i, _ -> i % 2 == 0 } println(evenPositions) // Both at once: withIndex(), then filter and map val longOnes = words.withIndex() .filter { it.value.length > 5 } .map { "${it.index}=${it.value}" } println(longOnes) // Find an index instead of looping for it println(words.indexOfFirst { it.startsWith("s") }) println(words.indexOfLast { it.length == 6 }) println(words.indexOfFirst { it.startsWith("x") }) // foldIndexed carries a running result val weighted = listOf(3, 1, 4).foldIndexed(0) { i, acc, n -> acc + i * n } println(weighted) // The trap: indexOf finds the first match, not the current position val letters = listOf("a", "b", "a") for (x in letters) print("${letters.indexOf(x)} ") println("(indexOf)") letters.forEachIndexed { i, _ -> print("$i ") } println("(forEachIndexed)") }
Output
mapIndexed numbers the words from 1:kotlin, and filterIndexed keeps positions 0, 2 and 4. The withIndex() chain keeps the original positions of the long words, 0=kotlin, 3=groovy and 4=clojure, which a plain filter followed by mapIndexed would renumber. indexOfFirst finds scala at 2, indexOfLast finds groovy at 3, and no match gives -1. The fold computes 0×3 + 1×1 + 2×4 = 9. The last two lines show a common bug: calling indexOf(x) inside the loop prints 0 1 0 because the second a is found at position 0; the real positions are 0 1 2.
7Which should you use?
| Method | Gives you | break / continue | Best for |
|---|---|---|---|
| for ((i, x) in list.withIndex()) | Index and element | Yes | Most loops that need the index |
| list.forEachIndexed { i, x -> } | Index and element | No; return@forEachIndexed skips | The end of a call chain |
| for (i in list.indices) | Index only | Yes | Writing back, neighbors, two lists |
| for (i in 0 until n), 0..<n | 0 to n - 1 | Yes | Counting; the C-style for loop |
| n downTo 0, indices.reversed() | Counts down | Yes | Backwards; removing by index |
| mapIndexed, filterIndexed | A new list | Not needed | Building a result from positions |
| list.indexOf(x) in a loop | First match only | Wrong with duplicates | Avoid: use withIndex() |
Frequently asked questions
How do I write a C-style for loop in Kotlin?
Kotlin has no for (int i = 0; i < n; i++). Write for (i in 0 until n) or for (i in 0..<n) for 0 to n - 1, for (i in 0 until n step 2) for a bigger stride and for (i in n - 1 downTo 0) to count down. The loop variable is read-only, so i += 2 in the body fails with 'val' cannot be reassigned.; when the stride changes as you go, use a while loop with a var.
How do I make the index start at 1?
The index from withIndex(), forEachIndexed and mapIndexed always starts at 0, so add 1 where you show it: println("${i + 1}. $item"). If you would rather count from 1, loop over 1..list.size and read list[i - 1].
Can I use break inside forEachIndexed?
No. The body is a lambda, so a break there, with no loop around it, fails with 'break' and 'continue' are only allowed inside loops.. return@forEachIndexed skips to the next element like continue, but nothing stops it early. When you need break, write for ((i, item) in list.withIndex()) instead.
How do I loop from 10 down to 0 in Kotlin?
Use for (i in 10 downTo 0). Writing 10..0 gives an empty range, so the loop never runs and nothing warns you. Add step 2 for every second number; the step must be positive even when counting down, and 10 downTo 0 step -2 throws IllegalArgumentException: Step must be positive, was: -2..
Does for (i in list.indices) create a range object?
No. A for loop over an Int range such as 0 until n, 1..n, n downTo 0 or list.indices is compiled to a plain counting loop with no iterator, so it costs the same as the Java loop it replaces. A range you store in a variable or pass to a function is a real IntRange object.
How do I loop over a range of decimals, like 0.0 to 1.0?
for (x in 0.0..1.0) does not compile: the error is For-loop range must have an 'iterator()' method., because a Double range can be checked with in but not iterated. Loop over whole numbers and scale them, for example for (i in 0..4) { val x = i * 0.25 }, which also avoids adding up rounding errors step by step.
How do I get the index of an element without a loop?
Use list.indexOf(x) for an equal element, or indexOfFirst { … } and indexOfLast { … } for a condition. All of them return -1 when nothing matches. Inside a loop, do not call indexOf on the current element to learn its position: with duplicates it returns the first match. Use withIndex() instead.
Run it yourself
Open any of these in the full Kotlin editor to tweak, run and share.
Kotlin playground