HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to KotlinVariables (val / var)Data TypesStringsListsConditions (if / when)Loops (for / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables & Types
🔢 Numbers & Math
✍️ String
📚 Collection
🔀 Condition & Loop
🧩 Function
Kotlin›Lists

Lists

Immutable lists with listOf, mutable lists with mutableListOf; element access and size.

Simple enough for a 5-year-old to understand

Create and access a list

listOf produces an immutable list. Elements are accessed using index numbers starting from zero.

Example code
1
val colors = listOf("red", "purple", "green")
A list with three elements.
DataA list with three elements.
2
println(colors[0])
First element: red
Output / InputFirst element: red
3
println(colors.size)
Number of elements: 3
Output / InputNumber of elements: 3
DataOutput / Input
💡 Hint: The first element is at index zero — this is the most common mistake.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.How do you access the first element in a three-element list?

About this topic

Kotlin collections are divided into two types: mutable and immutable. A list created with listOf is read-only; you cannot add or remove elements. A list created with mutableListOf is mutable.

This distinction is at the type level and is intentional. When you pass an immutable list to a function, you know from the type that the function will not corrupt your list. The default choice is the immutable list; you switch to the other when the need for modification arises.

Lists are zero-indexed. Going out of bounds produces a runtime error; if you don't want this, there are getOrNull and getOrElse methods that provide safe access.

What you will learn

  • Creating lists and accessing elements
  • The difference between mutable and immutable lists
  • Adding and removing elements
  • Iterating over a list
  • Safe access methods

Who is this for?

  • Those who will work with data lists
  • Those who confuse collection types
  • Those who get out-of-bounds errors

When to use?

Lists are used for ordered data that can contain duplicates; if uniqueness is required, Set is appropriate, and if key-value mapping is required, Map is suitable.

Returning an immutable type when returning a collection from a function prevents the caller from corrupting the contents.

Common mistakes

Wrong

val items = listOf("a", "b")
items.add("c")

listOf produces an immutable list and the add method does not exist on this type; you get an "Unresolved reference: add" error. The error is not because of val, but because of the list's type — writing var instead of val does not solve the problem.

Correct

val items = mutableListOf("a", "b")
items.add("c")

Wrong

val items = listOf("a", "b")
println(items[5])

The list only has indices 0 and 1; when 5 is requested, an IndexOutOfBoundsException is thrown and the program stops. If the index comes from outside, it is necessary to check before accessing or use a safe access method.

Correct

val items = listOf("a", "b")
println(items.getOrNull(5) ?: "none")

Wrong

val items = mutableListOf(1, 2, 3, 4)
for (item in items) {
  if (item % 2 == 0) items.remove(item)
}

Removing elements while iterating over a list produces a ConcurrentModificationException; the collection is not allowed to change during iteration. The correct way is to create a new list by filtering out what will be removed or to use removeAll.

Correct

val items = mutableListOf(1, 2, 3, 4)
items.removeAll { it % 2 == 0 }

Frequently asked questions

Is listOf truly immutable?

Its interface does not expose modification methods, so you cannot modify it from Kotlin code. However, since it is backed by a Java collection underneath, it can theoretically be modified from Java. It is safe in practice, but you shouldn't think of it as "completely immutable".

How do I get the index while iterating over a list?

You use forEachIndexed or withIndex; both provide the sequence number and the element together at each step. There is no need to manually maintain a counter, which prevents counter errors.

When should map and filter be used?

map is used to transform every element, and filter is used to select the ones that match a condition. Both return a new list and do not change the original. Compared to writing a loop and manually populating a list, it is both shorter and directly expresses the intent.

Summary

listOf produces an immutable list, mutableListOf produces a mutable list.

There is no add method in an immutable list.

Out-of-bounds access produces a runtime error.

Deleting elements while iterating throws an error.

getOrNull provides safe access.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code