Kotlin List – Remove an Element

We can modify the contents of a List only if the list is mutable.

To remove a specific element from a Mutable List in Kotlin, call remove() function on this list object and pass the element, that we would like to remove, as argument.

The syntax of remove() function is

MutableList.remove(element)

Examples

In the following program, we will create a mutable list with some elements in it. We shall then remove the element 9 from this list using remove() function.

Main.kt

fun main(args: Array<String>) {
    val mutableList: MutableList<Int> = mutableListOf(1, 4, 9, 16, 25)
    println("List before removing : " + mutableList)
    mutableList.remove(9)
    println("List after  removing : " + mutableList)
}

Output

List before removing : [1, 4, 9, 16, 25]
List after  removing : [1, 4, 16, 25]

If specified element is not present in this list, then the original list remains unchanged.

In the following program, we will try to remove the element 64, which is not present in the list.

Main.kt

fun main(args: Array<String>) {
    val mutableList: MutableList<Int> = mutableListOf(1, 4, 9, 16, 25)
    println("List before removing : " + mutableList)
    mutableList.remove(64)
    println("List after  removing : " + mutableList)
}

Output

List before removing : [1, 4, 9, 16, 25]
List after  removing : [1, 4, 9, 16, 25]

If the element that we would like to remove is present more than once in the list, only the first occurrence is removed from the list.

In the following program, we will try to remove the element 9, which is present twice in the list. Only the first occurrence should be removed.

Main.kt

fun main(args: Array<String>) {
    val mutableList: MutableList<Int> = mutableListOf(1, 4, 9, 16, 25, 9)
    println("List before removing : " + mutableList)
    mutableList.remove(9)
    println("List after  removing : " + mutableList)
}

Output

List before removing : [1, 4, 9, 16, 25, 9]
List after  removing : [1, 4, 16, 25, 9]
ADVERTISEMENT

Conclusion

In this Kotlin Tutorial, we learned how to remove a specific element from a mutable list in Kotlin, using remove() function, with the help of example programs.