Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 134 ยท Collections

Lists

Learn Kotlin lists: listOf and mutableListOf, indexing, getOrNull, subList, sorting, binarySearch, removing elements safely, destructuring and common mistakes, with runnable code.

The List is the collection you will use most. It keeps its elements in a fixed order, lets you reach any element by position, and happily holds duplicates. If you have ever used an array in another language, a Kotlin list is what you actually wanted: it grows, it knows its own size, and it comes with dozens of helpful functions.

This lesson covers creating lists, reading elements safely, slicing, adding and removing, sorting and searching, and the destructuring trick for small lists. It builds on Collections Overview, and the heavy transformation functions such as map and filter get their own lesson in Collection Transformations.

Creating and reading

listOf(...) creates a read-only list, mutableListOf(...) one you can change. Indexes start at 0.

Kotlin Reading a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is 4, Mercury, Mercury, Mars, 0..3, 3, false, true, 3 and -1. indexOf returns -1 when the element is missing, a convention you will see in many languages. planets[0] is shorthand for planets.get(0).

Out-of-range indexes

Asking for an index that does not exist throws an exception at run time:

Kotlin IndexOutOfBoundsException (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program stops with Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4, followed by a stack trace whose MainKt.main(main.kt:3) line points at the guilty line. (Another list implementation would throw its parent type, IndexOutOfBoundsException, with a similar message.) Valid indexes are 0 to lastIndex.

When the position might be wrong, use the safe functions instead of catching the exception:

Kotlin Safe access

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You get java, null, none, java and nothing here. The names ending in OrNull return null instead of throwing, and combine well with the Elvis operator ?: from Null Safety. Note that first() and last() themselves throw NoSuchElementException on an empty list.

Changing a mutable list

A MutableList supports adding, inserting, replacing and removing:

Kotlin Changing a mutable list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is [start, a, B, c, d], then start, [a, B, d], then [a, B, d, y] and true. Two things to note: add(0, "start") inserts at an index and pushes the rest to the right, and remove(element) removes the first match by value while removeAt(index) removes by position.

The remove trap on lists of Int

For a MutableList<Int>, remove and removeAt are different on purpose, and mixing them up is a classic bug:

Kotlin remove versus removeAt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first call removes the value 1 and prints [10, 20, 30]. The second removes the element at index 1 (the 20) and prints [10, 30]. Kotlin avoids Java's overload ambiguity by giving the by-index version its own name, removeAt. Always pick the one that says what you mean.

Adding without mutating

On a read-only list, + and - return a new list:

Kotlin
val base = listOf(1, 2, 3)
val more = base + 4          // [1, 2, 3, 4]
val fewer = base - 2         // [1, 3]
val joined = base + listOf(9, 9)

base itself is untouched. This style is natural in functional code, but copying a long list for every added element is slow (O(n) per addition). Inside a loop that builds a big result, use a MutableList or buildList.

Slicing: subList, take, drop, slice

Kotlin Taking parts of a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The results are [b, c, d], [a, b], [e, f], [e, f], [a, b], [a, c, e], [b, c, d] and [[a, b, c, d], [e, f]]. subList(from, to) includes from and excludes to. The functions take, drop, takeLast and dropLast never throw if you ask for more elements than exist; they just return what is there.

A subtle point: subList returns a view of the original, not a copy. Changes to the underlying list can make the view fail with ConcurrentModificationException. Call .toList() on it if you want an independent copy.

Sorting

Sorting comes in two flavours. The sorted... functions return a new list and leave the original alone, while sort... functions reorder a mutable list in place. The details, such as custom comparators, are in Sorting and Comparators.

Kotlin Sorting a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You see [banana, fig, kiwi, pear], [pear, kiwi, fig, banana], [fig, pear, kiwi, banana] (the sort is stable: pear and kiwi both have length 4 and keep their original order), [kiwi, banana, fig, pear], the untouched original [pear, fig, banana, kiwi], then [10, 30, 40] and [40, 30, 10], and finally [10, 30, 40] again. We sorted the shuffled list again because a seeded shuffle's exact order is a detail we do not want to rely on.

Searching

For an unsorted list, indexOf, find and contains do a linear scan. For a sorted list you can use binarySearch, which is much faster for large lists:

Kotlin Searching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This prints 3, -3, Grace, 2, 2 and 3. binarySearch returns the index when found. If not found, it returns -(insertionPoint) - 1: 6 would be inserted at index 2, so you get -3. Binary search on an unsorted list returns garbage without any error, so only use it when you know the order. More search functions are in Accessing and Searching.

Destructuring

For lists of known small size you can unpack the first components into variables. Lists support component1() to component5():

Kotlin Destructuring a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is red, green, blue, 4 and 14/06/2025. The underscore skips an element you do not need. Destructuring is index-based and does not check the size ahead of time: val (a, b) = listOf(1) throws an IndexOutOfBoundsException at run time, so use it for data whose shape you trust, such as the result of split on a known format. See Pairs, Triples and Destructuring.

Looping with index and in reverse

Kotlin Index loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output lines are 0=x 1=y 2=z , 0:x 1:y 2:z , zyx and [0x][1y][2z]. asReversed() is a cheap reversed view, while reversed() creates a new list.

Lists of lists and fixed-size lists

A grid is a list of lists. Create inner lists with the List(size) { ... } constructor function so that each row is a separate object:

Kotlin A 3x3 grid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The grid prints 0 1 2, 3 99 5 and 6 7 8. The last line prints [[0, 1], [0]]; because the lambda runs once per row, each row is its own list. (A common bug in other languages is repeating a single row object; the factory lambda avoids that.)

When to use a List, and when not

  • Use a list when order matters or duplicates are meaningful.
  • Use a Set if you mainly ask "is it in there?" on large data.
  • Use ArrayDeque if you add and remove at both ends, for example for queues.
  • Use an Array for fixed-size numeric data in hot loops.
  • Never modify a list while looping over it with for; see Mutable Collections and Iterators.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the index of the last element of listOf(5, 6, 7)?

    Indexes start at 0, so a list of three has indexes 0, 1 and 2; lastIndex is size - 1.
  2. 2. What does listOf(1, 2, 3).getOrNull(10) return?

    The OrNull variants return null instead of throwing.
  3. 3. Given val n = mutableListOf(10, 20, 30, 1), what does n.remove(1) remove?

    remove works by value. To remove by position, use removeAt(1).
  4. 4. What is true about words.sorted()?

    sorted returns a new list; sort on a MutableList sorts in place.
  5. 5. What does listOf(1, 2, 3, 4, 5).subList(1, 3) return?

    The start index is included and the end index is excluded, giving the elements at indexes 1 and 2.

Summary

  • listOf creates a read-only list and mutableListOf a changeable one; indexes start at 0.
  • Use getOrNull, firstOrNull and getOrElse when an index or element may not exist; plain indexing throws.
  • remove(element) removes by value, removeAt(index) by position.
  • sorted() returns a new list, sort() sorts a mutable list in place; both are stable.
  • binarySearch needs a sorted list and returns -(insertionPoint) - 1 when the value is missing.
  • subList and asReversed are views; use toList() for an independent copy.
  • Destructuring unpacks the first few elements by index.

Next: Sets