List Slicing With SubList
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 79 of 93.
Sometimes you need to extract a portion of a list rather than working with the entire collection. The subList() method lets you create a view of a specific range of elements from an existing list.
The subList() method takes two parameters: the starting index (inclusive) and the ending index (exclusive). This means the element at the start index is included, but the element at the end index is not:
val numbers = listOf(10, 20, 30, 40, 50)
val slice = numbers.subList(1, 4)
println(slice) // [20, 30, 40]In this example, subList(1, 4) extracts elements from index 1 up to (but not including) index 4. This gives us the second, third, and fourth elements.
The resulting sublist is a view of the original list, not a copy. This is important to understand when working with mutable lists, as changes to the original list can affect the sublist.
For most use cases with read-only lists, you can simply use it to access a range of elements:
val days = listOf("Mon", "Tue", "Wed", "Thu", "Fri")
val midWeek = days.subList(1, 4)
println(midWeek) // [Tue, Wed, Thu]Challenge
MediumYou will receive a list of integers and two indices representing a range. Extract a sublist using subList() and print the sum of 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 starting index (inclusive)
- Last line: the ending index (exclusive)
Output format:
Print the sum of the elements in the extracted sublist.
Example:
If the list is [5, 10, 15, 20, 25] with start index 1 and end index 4, the sublist would be [10, 15, 20] and the output should be 45.
Try it yourself
fun main() {
val n = readLine()!!.toInt()
val list = mutableListOf<Int>()
repeat(n) {
list.add(readLine()!!.toInt())
}
val startIndex = readLine()!!.toInt()
val endIndex = readLine()!!.toInt()
// TODO: Write your code below
// Use subList() to extract elements from startIndex to endIndex
// Calculate and print the sum of the extracted elements
}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