Question
In Kotlin, how can you access the current index while looping through a collection with a for-each style loop?
For example, I want to do something on every second iteration:
for (value in collection) {
if (iterationNo % 2 == 0) {
// do something
}
}
In Java, this is often done with a traditional indexed loop:
for (int i = 0; i < collection.length; i++) {
// use i
}
What is the Kotlin way to get the equivalent of i while iterating through a collection?
Short Answer
By the end of this page, you will understand how to access an element's index while looping in Kotlin. You will learn the most common options—withIndex(), forEachIndexed(), and a classic indexed loop—and when each one is most useful.
Concept
In Kotlin, a basic for (value in collection) loop gives you direct access to each element, but not its position. This is intentional: a for-each loop focuses on values, not indexes.
When you need both the element and its position, Kotlin provides built-in tools instead of making you manage a counter manually.
The most common choices are:
withIndex()forforloopsforEachIndexed()for functional-style iterationindicesor a classic range-based loop when you specifically need index-based access
Why this matters:
- Sometimes logic depends on position, such as every second item
- You may need to format output differently for the first or last item
- You may need both the index and value when processing lists
In Kotlin, the preferred approach is usually to choose the loop style that matches your intention:
- Need just values? Use
for (value in collection) - Need value and index? Use
withIndex()orforEachIndexed() - Need direct indexed access? Use
indices
This keeps your code readable and avoids unnecessary manual counters.
Mental Model
Think of a collection like a row of lockers.
- A plain
for (value in collection)loop lets you open each locker and look at what's inside. - An indexed loop also tells you the locker number.
If you only care about the contents, the locker number does not matter.
If you want to do something with every second locker, or print Item 0, Item 1, and so on, then you need both:
- the locker number = index
- the contents = value
Kotlin's withIndex() and forEachIndexed() are just convenient ways of giving you both pieces of information together.
Syntax and Examples
Using withIndex()
This is the most direct Kotlin-style solution for a for loop.
val collection = listOf("a", "b", "c", "d")
for ((index, value) in collection.withIndex()) {
if (index % 2 == 0) {
println("Index $index contains $value")
}
}
What this does
withIndex()pairs each element with its index(index, value)uses destructuring to extract both partsindex % 2 == 0checks for even indexes
Output:
Index 0 contains a
Index 2 contains c
Using forEachIndexed()
val collection = listOf("a", , , )
collection.forEachIndexed { index, value ->
(index % == ) {
println()
}
}
Step by Step Execution
Consider this example:
val collection = listOf("red", "blue", "green", "yellow")
for ((index, value) in collection.withIndex()) {
if (index % 2 == 0) {
println("$index -> $value")
}
}
Step-by-step
-
collectioncontains 4 items:- index
0=red - index
1=blue - index
2=green - index
3=yellow
- index
-
collection.withIndex()creates pairs like:(0, red)(1, blue)
Real World Use Cases
Getting the index during iteration is common in real programs.
UI rendering
You might style alternating rows differently:
items.forEachIndexed { index, item ->
val rowStyle = if (index % 2 == 0) "light" else "dark"
println("Render $item with $rowStyle style")
}
Numbered lists
val tasks = listOf("Write code", "Test app", "Deploy")
for ((index, task) in tasks.withIndex()) {
println("${index + 1}. $task")
}
Skipping or processing alternate items
val values = listOf(10, 20, 30, 40, 50)
for ((index, value) in values.withIndex()) {
if (index % 2 == 1) {
println()
}
}
Real Codebase Usage
In real Kotlin codebases, developers usually pick the iteration style based on intent.
Common patterns
1. Prefer value-only loops when index is unnecessary
for (user in users) {
println(user.name)
}
This is simpler and more readable.
2. Use withIndex() when writing a normal for loop
for ((index, user) in users.withIndex()) {
println("$index: ${user.name}")
}
This is common when you want a straightforward loop with index access.
3. Use forEachIndexed() in collection pipelines
users.forEachIndexed { index, user ->
if (user.isActive) {
println("Active user #$index: ${user.name}")
}
}
4. Use guard conditions with index-based logic
users.forEachIndexed { index, user ->
if (index == 0) return
println(user.name)
}
Common Mistakes
1. Expecting for (value in collection) to provide an index
This loop only gives you the value.
for (value in collection) {
// no index variable exists here
}
Fix
Use withIndex() or forEachIndexed().
for ((index, value) in collection.withIndex()) {
println(index)
}
2. Writing an invalid modulo condition
Broken code:
if (iterationNo % 2) {
// do something
}
In Kotlin, % returns a number, not a boolean.
Fix
Compare the result explicitly:
if (index % 2 == 0) {
// even index
}
3. Confusing iteration number with index
Indexes usually start at .
Comparisons
| Approach | Best when | Example | Notes |
|---|---|---|---|
for (value in collection) | You only need values | for (name in names) | Simplest and most readable |
for ((index, value) in collection.withIndex()) | You need both index and value in a normal loop | for ((i, v) in list.withIndex()) | Very idiomatic Kotlin |
collection.forEachIndexed { index, value -> } | You prefer lambda style | list.forEachIndexed { i, v -> } | Good for functional-style code |
for (i in collection.indices) | You need direct index access |
Cheat Sheet
Quick reference
Value only
for (value in collection) {
println(value)
}
Index + value with withIndex()
for ((index, value) in collection.withIndex()) {
println("$index -> $value")
}
Index + value with forEachIndexed()
collection.forEachIndexed { index, value ->
println("$index -> $value")
}
Index only
for (i in collection.indices) {
println(i)
}
Every second item
Even indexes:
if (index % 2 == 0)
Odd indexes:
(index % == )
FAQ
How do I get the index in a Kotlin for-each loop?
Use withIndex() in a for loop or forEachIndexed() in a lambda-based loop.
What is the Kotlin equivalent of Java's for (int i = 0; i < length; i++)?
Usually for (i in collection.indices) or for ((i, value) in collection.withIndex()), depending on whether you need the value directly.
How do I process every second element in Kotlin?
Use the index and test it with modulo:
if (index % 2 == 1)
or
if (index % 2 == 0)
depending on whether you want odd or even positions.
Is withIndex() better than a manual counter?
Usually yes. It is clearer, less error-prone, and more idiomatic in Kotlin.
Can I modify a list while using withIndex()?
You can read values easily, but if you need to update by position, looping over is often more appropriate.
Mini Project
Description
Build a small Kotlin program that prints a numbered to-do list and highlights every second item. This helps you practice getting both the index and the value during iteration, which is a common task in real applications such as rendering UI lists, formatting reports, or processing rows of data.
Goal
Create a Kotlin program that loops through a list of tasks, prints each task with its number, and marks every second task differently.
Requirements
- Create a list with at least five task names.
- Loop through the list using a Kotlin approach that gives both index and value.
- Print each task as a numbered item starting from 1.
- Add a label like
(even index)or(odd index)based on the position. - Only print a special message for every second item.
Keep learning
Related questions
Android AlarmManager Example: Scheduling Tasks with AlarmManager
Learn how to use Android AlarmManager to schedule tasks, set alarms, and handle broadcasts with a simple beginner example.
Can You Extend a Data Class in Kotlin? Inheritance, Limits, and Better Alternatives
Learn why Kotlin data classes cannot be extended, what causes the component function clash, and which alternatives to use instead.
Difference Between List and Array in Kotlin
Learn the difference between List and Array in Kotlin, including mutability, size, APIs, performance, and when to use each one.