Menu
Coddy logo textTech

WithIndex Method

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 75 of 93.

When iterating over a list, you often need to know not just the element, but also its position. The withIndex() method gives you both at once.

Call withIndex() on any list to get pairs of index and value:

val colors = listOf("Red", "Green", "Blue")
for ((index, color) in colors.withIndex()) {
    println("$index: $color")
}
// Output:
// 0: Red
// 1: Green
// 2: Blue

Notice the syntax inside the parentheses: (index, color). This is called destructuring, which unpacks the index and value into separate variables. You can name these variables whatever makes sense for your code.

This approach is cleaner than manually tracking an index with a counter variable. It's especially useful when you need to display numbered lists or perform different actions based on position:

val tasks = listOf("Wake up", "Exercise", "Eat breakfast")
for ((i, task) in tasks.withIndex()) {
    println("Step ${i + 1}: $task")
}
// Output:
// Step 1: Wake up
// Step 2: Exercise
// Step 3: Eat breakfast
challenge icon

Challenge

Medium

You will receive a list of student names as input. Read the number of students first, then read each name.

Using withIndex(), print each student with their rank number (starting from 1, not 0).

Input format:

  • First line: an integer n representing the number of students
  • Next n lines: student names (strings)

Output format:

Print each student on a separate line in the format:

Rank 1: Alice
Rank 2: Bob
Rank 3: Charlie

Remember that withIndex() gives you indices starting from 0, so you'll need to adjust for rank numbers starting from 1.

Try it yourself

fun main() {
    // Read the number of students
    val n = readLine()!!.toInt()
    
    // Read student names into a list
    val students = mutableListOf<String>()
    for (i in 1..n) {
        students.add(readLine()!!)
    }
    
    // TODO: Write your code below
    // Use withIndex() to iterate through students and print their rank
    // Remember: withIndex() gives indices starting from 0, but ranks should start from 1
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground