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: BlueNotice 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 breakfastChallenge
MediumYou 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
nrepresenting the number of students - Next
nlines: student names (strings)
Output format:
Print each student on a separate line in the format:
Rank 1: Alice
Rank 2: Bob
Rank 3: CharlieRemember 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
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function13Iterating Over Sequences
Iterating Over ElementsWithIndex MethodIterating Over Strings P1Iterating Over Strings P2Recap - Indexed Letters2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground