1. Indices in a List: when you need them
When you first learn that a List has indexed access, you want to write something like: “I’m a programmer, so I’ll iterate by indices.” I get it. I had that feeling too — as if otherwise the IDE would get offended. But in Kotlin, indexed iteration is a tool, not a lifestyle.
List is an ordered collection: elements are stored in a defined order, and you can access them by position. Indices start at 0, and the last valid index is lastIndex, which equals size - 1. This gives us two ways of thinking: “iterate by values” (most often simpler) and “iterate by positions” (needed only when the position actually participates in the logic).
Let’s agree on a practical rule right away: if you don’t need the index — don’t take the index. The code will be shorter, calmer, and less eager to crash.
fun main() {
val products = listOf("milk", "bread", "tea")
for (p in products) {
println(p)
}
// milk
// bread
// tea
}
Iteration by values — the “default mode”
In Kotlin, the language designers are clearly hinting: “if you can write it simply — write it simply.” And for (item in list) is exactly that case. This iteration works because List is Iterable, which means it has an iterator that for receives implicitly.
This style is good because it’s almost impossible to make a boundary mistake. No i + 1, no size - 1, no “oops, I accidentally wrote <= instead of <.” You walk through the elements, and that’s it.
Suppose in a practical mini app we have a list of tasks (no classes yet, just strings):
fun main() {
val tasks = listOf("pay rent", "buy tea", "learn Kotlin")
for (task in tasks) {
println("TODO: $task")
}
// TODO: pay rent
// TODO: buy tea
// TODO: learn Kotlin
}
Reads perfectly. But sometimes we still need an index: for example, to print “1. … 2. … 3. …”, or to access a “neighbor” element, or to delete by number (deletion is a separate story, but we already need numbering now). That’s when indices, lastIndex, and withIndex() show up.
size, lastIndex, and an empty list: where boundary errors begin
Lists have two quantities that beginners constantly confuse: size and lastIndex. It usually looks like this: “if the size is 3, then indices are 0..3.” And right here Kotlin, like a strict teacher, pulls out the grade book and gives you an IndexOutOfBoundsException.
The correct model is: size is the number of elements, and lastIndex is the last valid index, and it equals size - 1. That is, if there are 3 elements, indices are 0, 1, 2.
It gets especially interesting when the list is empty. Then size = 0, and lastIndex = -1. That sounds strange (“minus first element?”), but in fact it’s convenient: many ranges in Kotlin become empty with such bounds, and the loop simply doesn’t run — without extra checks.
Here’s a mini table that’s useful to keep in mind (not as a mantra, but as a “common-sense cheat sheet”):
| List | size | lastIndex | Valid indices |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
none |
Now let’s show the typical “confused size and lastIndex” mistake:
fun main() {
val items = listOf("A", "B", "C")
// BAD: i will go 0,1,2,3 — but index 3 does not exist
for (i in 0..items.size) {
println(items[i])
}
}
This code will crash at i == 3, because items[3] doesn’t exist. The solution is to use correct bounds — and that’s where indices comes in.
indices: safe bounds for iterating by indices
When you iterate a list by indices, your real task is to pick the range of valid indices. Kotlin gives you a ready-made solution: the indices property, which returns the range of correct indices, and you can use it directly in for.
The key convenience of indices is that it automatically works correctly for an empty list and for a list of any size. You don’t think about 0..lastIndex, you just say: “iterate over the valid indices.”
fun main() {
val items = listOf("milk", "bread", "tea")
for (i in items.indices) {
println("$i -> ${items[i]}")
}
// 0 -> milk
// 1 -> bread
// 2 -> tea
}
An important point here: if you’re writing items[i], you must be sure that i is valid. indices is exactly what says: “I guarantee validity.”
This style is needed when the index participates in logic. For example, you want to look at the “current and next element” (the simplest example is building pairs). Without an index it’s harder:
fun main() {
val items = listOf("A", "B", "C")
for (i in 0 until items.lastIndex) {
val left = items[i]
val right = items[i + 1]
println("$left + $right")
}
// A + B
// B + C
}
Note: here I used items.lastIndex as the bound (otherwise i + 1 can go out of range). The very fact that you write i + 1 is already a signal: “in this loop you need to think about bounds.” That’s a normal price for more complex logic.
If until feels “scary” (or you don’t have a good feel for it yet), you can write it like this — carefully:
fun main() {
val items = listOf("A", "B", "C")
for (i in items.indices) {
if (i == items.lastIndex) continue
println("${items[i]} + ${items[i + 1]}")
}
// A + B
// B + C
}
Yes, we added an if, but we stay within indices and explicitly protect ourselves from the last element.
2. Index vs. number: don’t mix internal and external
A human-facing number and a Kotlin index are different things
When you build a console app, you quickly find out: users (and instructors grading your work) love numbering that starts at one. Kotlin, like a typical engineer, starts at zero. And if you don’t decide with yourself who’s in charge here, you’ll keep deleting “the wrong task.”
The idea is simple: an index is the internal address of an element in the list (0..lastIndex), while a number is the external, human-readable identifier (1..size). Almost always, when you print a list, you print the number, not the index.
Here is “index-based” output, which looks a bit sad:
fun main() {
val tasks = listOf("pay rent", "buy tea")
for (i in tasks.indices) {
println("$i. ${tasks[i]}")
}
// 0. pay rent
// 1. buy tea
}
And here is “human” output — we just add + 1:
fun main() {
val tasks = listOf("pay rent", "buy tea")
for (i in tasks.indices) {
println("${i + 1}. ${tasks[i]}")
}
// 1. pay rent
// 2. buy tea
}
It looks like a small detail, but for commands like remove 2 it’s a matter of program survival without drama. Remember it as a rule: input is a “number,” storage is an “index,” conversion is “number - 1.”
withIndex(): index + value without manual list[i]
A loop over indices works, but it has one small problem: you keep seeing tasks[i], and it turns the code into “lots of square brackets.” In Kotlin, for more readable “index + value” iteration, there’s withIndex() — a standard function that lets you iterate over pairs “index and element” right in for.
The nicest bonus of withIndex() is that you can use destructuring: for ((index, value) in list.withIndex()). And the code becomes conversational: “for each index and value…”.
fun main() {
val tasks = listOf("pay rent", "buy tea", "learn Kotlin")
for ((index, task) in tasks.withIndex()) {
println("${index + 1}. $task")
}
// 1. pay rent
// 2. buy tea
// 3. learn Kotlin
}
Technically, withIndex() gives you an object you can iterate over, and inside it contains elements with indices. But for you right now, the practice matters more: this style is more readable when you need both.
One more note: withIndex() looks especially nice when the names are meaningful. If you write for ((i, x) in ...) — that’s still tolerable. But if you write for ((a, b) in ...) and then do a + 1 and print b, a person nearby will start suspecting you’re encrypting a message to an alien civilization.
3. How to choose an iteration style
When you see three iteration methods, a beginner starts thinking they must pick “the most correct one” once and for all. Relax: there isn’t a single correct one. There is a suitable one for the situation. The good news is that the selection criteria are very simple, and you can turn them into a mini algorithm for your brain.
Imagine you’re writing code and asking yourself one question: “Do I need the index?” If not — iterate by values. If yes — ask a second: “Do I need the index for access to neighbors/positions, or just to print a number?” If it’s just printing, most often withIndex() is more convenient. If it’s positional logic — take indices.
You can depict it with a flowchart like this:
flowchart TD
A["Need to iterate over a List"] --> B{"Need an index?"}
B -->|No| C["for (x in list)"]
B -->|Yes| D{"Why the index?"}
D -->|Only number/printing| E["for ((i, x) in list.withIndex())"]
D -->|Positional logic: neighbors, i+1, i-1| F["for (i in list.indices) { ... list[i] ... }"]
The point isn’t to worship the diagram, but to avoid “index loops out of habit.” Kotlin reads very well when you write only what’s minimally necessary.
4. Mini project: the list command in a Task CLI
Now we’ll carefully apply the new material to our small app. Let it be a simple “Task CLI”: we store tasks in a MutableList<String>, add commands, and the most important command at this stage is to display the list nicely. If the list is displayed poorly, the user has nothing to enter for remove later, and they get annoyed (and an annoyed user is scarier than a compiler).
Let’s start with a printing function. Note: I accept a List<String>, not a MutableList<String>, because printing should not modify the list. This is a good habit: “take the narrowest type you need for the task.”
fun printTasks(tasks: List<String>) {
if (tasks.isEmpty()) {
println("任務清單為空。")
return
}
for ((index, task) in tasks.withIndex()) {
println("${index + 1}. $task")
}
}
Now an example main that demonstrates it:
fun main() {
val tasks = mutableListOf<String>()
tasks.add("pay rent")
tasks.add("buy tea")
printTasks(tasks)
// 1. pay rent
// 2. buy tea
}
And now a small but important detail: sometimes you want to print not only the task, but also some service information tied to the index. For example, a hint like “internal index” (for debugging) or a format like “#0001.” For such formatting, withIndex() is also ideal — you already have the index anyway.
fun main() {
val tasks = listOf("pay rent", "buy tea")
for ((index, task) in tasks.withIndex()) {
val debugIndex = index
println("[$debugIndex] ${index + 1}. $task")
}
// [0] 1. pay rent
// [1] 2. buy tea
}
In a real app, of course, you won’t print [0], but as an educational “X-ray” it’s useful: you literally see the difference between “index vs. number.”
5. Typical mistakes when iterating over a List
Mistake #1: using size as the last index.
This is the most common and the most frustrating mistake, because it looks logical: “if there are size elements, then the last index is size.” But no: indices start at 0, so the last valid index is lastIndex, i.e. size - 1. The fix is simple: in index-based loops use indices or explicitly lastIndex, not size.
Mistake #2: printing indices to the user, but accepting numbers from them (or vice versa).
If you print 0. … and the user enters remove 1, you’ll inevitably get “the wrong element” and a lot of confusion. The solution is to agree on a convention: show the user numbering starting at 1, and inside the program use indices starting at 0. And always convert: index = number - 1.
Mistake #3: using indexed iteration “on autopilot” even though the index isn’t needed anywhere.
Code like for (i in tasks.indices) println(tasks[i]) isn’t broken, but it’s heavier to read than for (task in tasks) println(task). If the index doesn’t participate in logic, iterating by values is better: fewer chances to accidentally add “dangerous index math” and get a boundary error.
Mistake #4: trying to put too much logic inside withIndex() and losing meaning.
withIndex() is good when you print “number + value” or do a small tie to position. But if complex arithmetic, neighbor checks, and several temporary variables start appearing inside the loop, it’s often easier to switch to indices, where you explicitly control access via list[i] and can carefully handle i - 1 and i + 1.
Mistake #5: not thinking about an empty list in user output.
Technically, for (i in list.indices) on an empty list simply won’t execute, and that’s safe. But the UX is strange: the user entered list, and the program “silently said nothing.” So for a command-line app it’s better to explicitly handle isEmpty() and print a clear message like “The list is empty.”
GO TO FULL VERSION