Menu
Coddy logo textTech

List Slicing With Take Drop

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 80 of 93.

Kotlin provides two simpler methods for extracting portions of a list when you only need elements from the beginning or end: take() and drop().

The take() method returns a new list containing the first n elements:

val numbers = listOf(10, 20, 30, 40, 50)
val firstThree = numbers.take(3)
println(firstThree)  // [10, 20, 30]

The drop() method does the opposite. It skips the first n elements and returns the rest:

val numbers = listOf(10, 20, 30, 40, 50)
val afterTwo = numbers.drop(2)
println(afterTwo)  // [30, 40, 50]

Unlike subList(), these methods return independent copies rather than views. They're also more readable when you simply want "the first few" or "everything except the first few" elements.

You can combine both methods to extract a middle section:

val letters = listOf("A", "B", "C", "D", "E")
val middle = letters.drop(1).take(3)
println(middle)  // [B, C, D]

If you request more elements than exist, these methods simply return what's available without throwing an error:

val short = listOf(1, 2)
println(short.take(10))  // [1, 2]
println(short.drop(10))  // []
challenge icon

Challenge

Medium

You will receive a list of integers and two numbers: how many elements to drop from the beginning and how many elements to take after dropping.

Use drop() and take() together to extract a middle section of the list, then print the extracted elements.

Input format:

  • First line: an integer n representing the number of elements
  • Next n lines: integers to add to the list
  • Next line: the number of elements to drop from the beginning
  • Last line: the number of elements to take after dropping

Output format:

Print the resulting list in Kotlin's default list format.

Example:

If the list is [10, 20, 30, 40, 50, 60], drop is 2, and take is 3, the output should be:

[30, 40, 50]

Try it yourself

fun main() {
    // Read the number of elements
    val n = readLine()!!.toInt()
    
    // Read the list elements
    val list = mutableListOf<Int>()
    for (i in 1..n) {
        list.add(readLine()!!.toInt())
    }
    
    // Read drop and take values
    val dropCount = readLine()!!.toInt()
    val takeCount = readLine()!!.toInt()
    
    // TODO: Write your code below
    // Use drop() and take() to extract the middle section
    
    
    // Print the result
    println(result)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground