Remove last element of a list in Kotlin
In this quick article, we’ll see how to remove the last element from a list in Kotlin.
Kotlin MutableList efficiently supports deletion at the end. This can be done in several ways, as shown below:
1. Using removeLast() function
The simplest solution to remove the last element from a list in Kotlin is to use the removeLast() function.
|
1 2 3 4 5 6 7 |
fun main() { val list: MutableList<String> = mutableListOf("A", "B", "C", "D", "E") println("Original List: $list") list.removeLast() println("Modified List: $list") // [A, B, C, D] } |
2. Using removeAt() function
You can also use the removeAt() function, which removes an element from the specified position in the list. To remove the last element, you need to pass an index of the last element.
|
1 2 3 4 5 6 7 |
fun main() { val list: MutableList<String> = mutableListOf("A", "B", "C", "D", "E") println("Original List: $list") list.removeAt(list.size - 1) println("Modified List: $list") // [A, B, C, D] } |
3. Using remove() function
If your list contains all distinct elements, you can call the remove() function with the last element. This removes the first occurrence of the last element from the list.
|
1 2 3 4 5 6 7 |
fun main() { val list: MutableList<String> = mutableListOf("A", "B", "C", "D", "E") println("Original List: $list") list.remove(list.last()) println("Modified List: $list") // [A, B, C, D] } |
That’s all about removing the last element of a list in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)