Kotlin List
A Kotlin List is an ordered collection of elements. Each element has an integer index, starting at 0, and duplicate elements are allowed. The order of the elements is preserved, so you can retrieve an item by its position.
Kotlin provides two main list interfaces:
List<T>provides read-only access to its elements.MutableList<T>supports read and write operations such as adding, replacing, and removing elements.
A read-only List reference does not provide functions that modify the list. This is more precise than describing every List as immutable because the underlying collection or the objects stored in it may still be mutable.
This tutorial explains how to initialize Kotlin lists, access elements safely, add and remove items, search and filter values, create lists of objects, retrieve slices, iterate through elements, and convert lists to other collection types.
Initialize a Kotlin List with listOf() and mutableListOf()
Use listOf() to create a read-only list and mutableListOf() to create a mutable list. Kotlin can usually infer the element type from the supplied values.
In the following example,
var listA = listOf<String>("Example", "Program", "Tutorial")
var listB = mutableListOf("Example", "Program", "Tutorial")
listA has the type List<String>. Its elements can be read, but they cannot be added, removed, or replaced through this reference.
listB has the type MutableList<String> and supports list modification operations.
Prefer val when the variable does not need to refer to a different list. A mutable list assigned to val can still have its contents modified.
val names = mutableListOf("Asha", "Ravi")
names.add("Meera")
println(names)
[Asha, Ravi, Meera]
Create an empty Kotlin List
When a list starts without any values, specify its element type because Kotlin has no elements from which to infer the type.
val emptyNames: List<String> = emptyList()
val mutableNames = mutableListOf<String>()
Initialize a Kotlin List with the List constructor
The List(size) constructor creates a read-only list of the specified size. Its initializer function receives the index for each element.
val squares = List(5) { index -> index * index }
println(squares)
[0, 1, 4, 9, 16]
Get a Kotlin List Element by Index
Use get(index) or square brackets to retrieve an element. Kotlin list indexes start at 0, so the last valid index is list.size - 1, also available as list.lastIndex.
Kotlin Program – example.kt
fun main(args: Array<String>) {
//initialize list
var listA = listOf<String>("Example", "Program", "Tutorial")
//accessing elements using square brackets
println(listA[0])
//accessing elements using get()
println(listA.get(2))
}
Output
Example
Tutorial
The expression listA[0] returns the first element, while listA.get(2) returns the third element.
Access a Kotlin List safely with getOrNull()
Using get() or square brackets with an invalid index throws an IndexOutOfBoundsException. Use getOrNull() when an index may not exist, or getOrElse() when a fallback value is required.
val colors = listOf("Red", "Green", "Blue")
println(colors.getOrNull(5))
println(colors.getOrElse(5) { "Unknown" })
null
Unknown
Check Kotlin List Size, Indexes, and Empty State
The size property returns the number of elements. Use indices to obtain the valid index range, lastIndex for the final valid index, and isEmpty() or isNotEmpty() to check whether the list contains elements.
val languages = listOf("Kotlin", "Java", "Swift")
println(languages.size)
println(languages.indices)
println(languages.lastIndex)
println(languages.isNotEmpty())
3
0..2
2
true
Add Elements to a Kotlin MutableList
A read-only List<T> does not provide write operations. To append an item, create a MutableList<T> and call add(item).
Kotlin Program – example.kt
fun main(args: Array<String>) {
//initialize a mutable list
var listA = mutableListOf("Example", "Program", "Tutorial")
//add item to the list
listA.add("Sample")
//print the list
println(listA)
}
Output
[Example, Program, Tutorial, Sample]
The new item is appended to the end of the list. To insert an element at a particular position, pass the index as the first argument to add(). Use addAll() to insert multiple elements.
val numbers = mutableListOf(10, 40)
numbers.add(1, 20)
numbers.addAll(2, listOf(30, 35))
println(numbers)
[10, 20, 30, 35, 40]
Update and Remove Kotlin MutableList Elements
Replace an element using square brackets or set(index, value). Use remove(value) to remove the first matching value and removeAt(index) to remove the element at a specified position.
val tasks = mutableListOf("Plan", "Write", "Review", "Publish")
tasks[1] = "Draft"
tasks.remove("Review")
tasks.removeAt(0)
println(tasks)
[Draft, Publish]
Removing an element shifts the following elements to the left, so their indexes change. Other useful mutable-list operations include clear(), removeAll(), and retainAll().
Check Whether a Kotlin List Contains an Element
Call contains() to test whether a list contains a value. It returns true when a matching element is present and false otherwise. The in operator provides a shorter equivalent syntax.
Kotlin Program – example.kt
fun main(args: Array<String>) {
//create a list
var listA = listOf<String>("Example", "Program", "Tutorial")
//check if the list contains element "Program"
val b = listA.contains("Program")
//based on the result of contains(), print a message
if(b){
print("Program is present in the list.")
} else{
print("Program is not present in the list.")
}
}
Output
Program is present in the list.
Because "Program" is present, b is true and the first message is printed. The same test can be written as "Program" in listA.
Find an Element in a Kotlin List
The find() function returns the first element that satisfies a predicate. Inside the predicate, it represents the current element. If no element matches, find() returns null.
The following example finds the first element containing the string "am".
Kotlin Program – example.kt
fun main(args: Array<String>) {
//initialize the list
var listA = listOf<String>("Example", "Program", "Tutorial")
//find the element
val b = listA.find { it.contains("am") }
//print the element
print(b)
}
Output
Example
Use indexOf(value) when you need the position of a known value. It returns the first matching index or -1 when the value is absent. Predicate-based alternatives include indexOfFirst() and indexOfLast().
Filter Elements in a Kotlin List
The filter() function creates a new list containing every element that satisfies a predicate. It does not modify the source list.
In the following example, the predicate selects elements containing "am".
Kotlin Program – example.kt
fun main(args: Array<String>) {
//initialize a list
var listA = listOf<String>("Example", "Program", "Tutorial")
//filter the list
val b = listA.filter { it.contains("am") }
//print the filtered list
print(b)
}
Output
[Example, Program]
The resulting list contains only the elements that satisfy the predicate. Related operations include filterNot(), filterIndexed(), filterNotNull(), any(), all(), and none().
Transform a Kotlin List with map()
The map() function applies a transformation to every element and returns a new list of the transformed values.
val prices = listOf(20, 35, 50)
val doubledPrices = prices.map { it * 2 }
println(doubledPrices)
println(prices)
[40, 70, 100]
[20, 35, 50]
The original prices list remains unchanged. Use mapIndexed() when the transformation also requires each element’s index.
Create and Search a Kotlin List of Objects
A Kotlin list can store instances of a class or data class. Properties of each object can be used in predicates and transformations.
data class Student(val name: String, val score: Int)
fun main() {
val students = listOf(
Student("Anu", 82),
Student("Dev", 67),
Student("Sara", 91)
)
val highScorers = students.filter { it.score >= 80 }
val sara = students.find { it.name == "Sara" }
println(highScorers)
println(sara)
}
[Student(name=Anu, score=82), Student(name=Sara, score=91)]
Student(name=Sara, score=91)
Retrieve a Slice or Sublist from a Kotlin List
Use slice() to create a list containing elements at selected indexes. Use subList(fromIndex, toIndex) for a consecutive range in which the starting index is included and the ending index is excluded.
val letters = listOf("A", "B", "C", "D", "E")
println(letters.slice(1..3))
println(letters.subList(1, 4))
println(letters.take(2))
println(letters.drop(2))
[B, C, D]
[B, C, D]
[A, B]
[C, D, E]
slice(), take(), and drop() return new lists. A subList() is a view backed by the original list, so structural changes involving either list require care.
Sort and Reverse Kotlin Lists
Functions such as sorted(), sortedDescending(), sortedBy(), and reversed() return new lists. Mutable lists also provide in-place operations such as sort(), sortDescending(), and reverse().
val words = listOf("pear", "fig", "banana")
println(words.sorted())
println(words.sortedBy { it.length })
println(words.reversed())
println(words)
[banana, fig, pear]
[fig, pear, banana]
[banana, fig, pear]
[pear, fig, banana]
Iterate Through a Kotlin List with a for Loop
Use a for loop to process each element in order.
Kotlin Program – example.kt
fun main(args: Array<String>) {
//initialize a list
var listB = listOf<String>("Example", "Program", "Tutorial")
//for loop on list
for(item in listB){
println(item)
}
}
Output
Example
Program
Tutorial
When both the index and value are required, iterate over withIndex().
val fruits = listOf("Apple", "Mango", "Orange")
for ((index, fruit) in fruits.withIndex()) {
println("$index: $fruit")
}
0: Apple
1: Mango
2: Orange
Convert a Kotlin List to MutableList, Set, or Array
Kotlin provides conversion functions that return a new collection. Use toMutableList() when a writable copy is needed, toSet() to remove duplicate values, and toTypedArray() to create a typed array.
val numbers = listOf(10, 20, 20, 30)
val mutableNumbers = numbers.toMutableList()
val uniqueNumbers = numbers.toSet()
val numberArray = numbers.toTypedArray()
mutableNumbers.add(40)
println(mutableNumbers)
println(uniqueNumbers)
println(numberArray.contentToString())
[10, 20, 20, 30, 40]
[10, 20, 30]
[10, 20, 20, 30]
Kotlin List and MutableList Differences
| Feature | List<T> | MutableList<T> |
|---|---|---|
| Indexed element access | Yes | Yes |
| Duplicate elements | Allowed | Allowed |
| Add and remove elements | No write operations | Yes |
| Replace an element by index | No write operations | Yes |
| Common creation function | listOf() | mutableListOf() |
| Typical use | Expose values that callers only need to read | Maintain a collection whose contents must change |
Choose List when callers only need to read the collection. Choose MutableList when elements must be inserted, replaced, or removed. Further details are available in the official Kotlin list operations documentation.
Kotlin List Frequently Asked Questions
Is a Kotlin List immutable?
List<T> is a read-only interface. It does not expose functions for adding, removing, or replacing elements. However, this does not guarantee that the underlying collection or the objects stored in it can never change.
How do I add an item to a Kotlin List?
Use a MutableList and call add(). If the current value is a read-only list, create a mutable copy with toMutableList(). The expression list + item is another option when you want a new list without changing the original.
How do I avoid an index error when reading a Kotlin List?
Use getOrNull(index) to return null for an invalid index or getOrElse(index) to provide a fallback value. Direct access with list[index] throws an exception when the index is outside the valid range.
How do I get part of a Kotlin List?
Use slice() for selected indexes, subList() for a consecutive index range, take() for elements from the beginning, or drop() to skip elements from the beginning.
Kotlin List Tutorial QA Checklist
- Verify that examples distinguish the read-only
Listinterface fromMutableListwrite operations. - Confirm that every index example uses zero-based indexing and stays within
0..lastIndex. - Check that examples using an uncertain index demonstrate
getOrNull()orgetOrElse(). - Confirm that operations such as
filter(),map(), andsorted()are described as returning new lists. - Verify that
subList(fromIndex, toIndex)explains its inclusive starting index, exclusive ending index, and backed-view behavior.
Summary of Kotlin List Operations
In this Kotlin Tutorial on Kotlin List, we learned how to create read-only and mutable lists, retrieve elements by index, inspect list size, add and remove items, find and filter values, transform elements, work with lists of objects, retrieve slices, sort values, iterate with indexes, and convert a list to other collection types.
TutorialKart.com