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
MediumYou 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
nrepresenting the number of elements - Next
nlines: 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)
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input14Lists Advanced
List Slicing With SubListList Slicing With Take DropSequence OperatorsThe Contains MethodRecap - Search a Page3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground