How to Remove Element from List in Kotlin: Simple Guide
In Kotlin, you can remove an element from a list by using a
MutableList and calling functions like remove(element) to remove by value or removeAt(index) to remove by position. Immutable lists cannot be changed directly, so use mutable lists for removal operations.Syntax
To remove elements from a list in Kotlin, you need a MutableList. The main functions are:
remove(element): Removes the first occurrence of the specified element.removeAt(index): Removes the element at the specified index.removeIf { condition }: Removes all elements matching the condition.
kotlin
val list = mutableListOf("apple", "banana", "cherry") list.remove("banana") // Removes "banana" by value list.removeAt(0) // Removes element at index 0 ("apple") list.removeIf { it.startsWith("c") } // Removes elements starting with 'c'
Example
This example shows how to create a mutable list, remove elements by value and index, and print the list after each removal.
kotlin
fun main() {
val fruits = mutableListOf("apple", "banana", "cherry", "date")
println("Original list: $fruits")
fruits.remove("banana")
println("After removing 'banana': $fruits")
fruits.removeAt(1)
println("After removing element at index 1: $fruits")
fruits.removeIf { it.startsWith("a") }
println("After removing elements starting with 'a': $fruits")
}Output
Original list: [apple, banana, cherry, date]
After removing 'banana': [apple, cherry, date]
After removing element at index 1: [apple, date]
After removing elements starting with 'a': [date]
Common Pitfalls
One common mistake is trying to remove elements from an immutable list, which causes a compile error because List in Kotlin is read-only. Another is using removeAt with an invalid index, which throws an IndexOutOfBoundsException.
Always use MutableList if you want to remove elements, and check the index before using removeAt.
kotlin
fun main() {
val immutableList = listOf("a", "b", "c")
// immutableList.remove("a") // Error: Unresolved reference: remove
val mutableList = mutableListOf("a", "b", "c")
// Wrong index:
// mutableList.removeAt(5) // Throws IndexOutOfBoundsException
// Correct usage:
if (mutableList.size > 2) {
mutableList.removeAt(2)
}
println(mutableList)
}Output
[a, b]
Quick Reference
| Function | Description | Example |
|---|---|---|
| remove(element) | Removes first occurrence of element | list.remove("apple") |
| removeAt(index) | Removes element at given index | list.removeAt(0) |
| removeIf { condition } | Removes all elements matching condition | list.removeIf { it.length > 3 } |
Key Takeaways
Use MutableList to remove elements because List is read-only in Kotlin.
Use remove(element) to delete by value and removeAt(index) to delete by position.
Check list size before using removeAt to avoid errors.
removeIf lets you remove elements based on a condition easily.
Immutable lists cannot be changed; create a mutable copy if needed.