List access
- Kotlin course
- Beginner
- Lesson 61/116
- 5 min
Learn list access with get, indexOf and subList.
List access: get, indexOf, subList
There are several ways to reach a list element. get(i) (or [i]) returns the element at index i. indexOf(x) gives the first index where x appears, or -1 if not found. subList(from, to) returns the range [from, to) as a new list.
val fruits = listOf("apple", "banana", "cherry", "grape")
fruits.get(0) // "apple"
fruits.indexOf("banana") // 1
fruits.subList(1, 3) // [banana, cherry]Indexes start at 0 and end at size - 1. The end of the range (to) is exclusive; that is why subList(1, 3) takes indexes 1 and 2.
The range of subList: [from, to)
subList(from, to) includes index from and excludes index to. So subList(1, 3) gives indexes 1 and 2; index 3 is not included.
val f = listOf("a", "b", "c", "d", "e")
val middle = f.subList(1, 4) // [b, c, d]This half-open range matches Kotlin's 1..4 (closed) and 1 until 4 (open) ranges. It makes index math easier.
Practice Print the first fruit, the index and the slice
Create a listOf("apple", "banana", "cherry", "grape"). Use get(0) to assign the first fruit to first, indexOf("banana") for the index i, and subList(1, 3) for the slice. Print each on its own line with println.
Starter code
fun main() {
val fruits = listOf("apple", "banana", "cherry", "grape")
// Get the first fruit, find the index of "banana", print the slice 1..3
}Sample solution
fun main() {
val fruits = listOf("apple", "banana", "cherry", "grape")
val first = fruits.get(0)
val i = fruits.indexOf("banana")
println(first)
println(i)
println(fruits.subList(1, 3))
}Expected output
apple 1 [banana, cherry]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match access expression to result
| Term | Meaning |
|---|---|
get(0) |
First element |
indexOf(x) |
Position of x (-1 if missing) |
subList(1, 3) |
Indexes 1 and 2 |
size - 1 |
Last index |
2 What does list.indexOf("missing") return?
- 0
- Throws an exception
- null
- -1 Correct answer
Explanation: indexOf returns -1 when not found; no null, no exception.
3 Fill in the blank: get the first element
val first = fruits.____(0)
val first = fruits.get(0)
Explanation: fruits.get(0) returns the first fruit.