Menu
Coddy logo textTech

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 icon

Challenge

Medium

You 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 n representing the number of elements
  • Next n lines: 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
    
}
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