Kotlin List dropLast()
Syntax & Examples


Syntax of List.dropLast()

The syntax of List.dropLast() extension function is:

fun <T> List<T>.dropLast(n: Int): List<T>

This dropLast() extension function of List returns a list containing all elements except last n elements.



✐ Examples

1 Example

In this example,

  • We create a list of integers list.
  • We use the dropLast function with the argument 2 to drop the last two elements from the list.
  • The resulting list result contains elements 1, 2, 3, 4.
  • Finally, we print the result list to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5, 6)
    val result = list.dropLast(2)
    print(result)
}

Output

[1, 2, 3, 4]

2 Example

In this example,

  • We create a list of characters list.
  • We use the dropLast function with the argument 3 to drop the last three elements from the list.
  • The resulting list result contains elements a.
  • Finally, we print the result list to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;)
    val result = list.dropLast(3)
    print(result)
}

Output

[a]

3 Example

In this example,

  • We create a list of strings list.
  • We use the dropLast function with the argument 1 to drop the last element from the list.
  • The resulting list result contains elements apple, banana, mango.
  • Finally, we print the result list to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(&quot;apple&quot;, &quot;banana&quot;, &quot;mango&quot;, &quot;avocado&quot;)
    val result = list.dropLast(1)
    print(result)
}

Output

[apple, banana, mango]

Summary

In this Kotlin tutorial, we learned about dropLast() extension function of List: the syntax and few working examples with output and detailed explanation for each example.