Menu
Coddy logo textTech

List Methods

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

Beyond adding and removing elements, lists come with helpful methods that let you query and transform their contents. These work on both List and MutableList.

To check if a list has any elements, use isEmpty() or isNotEmpty():

val tasks = listOf("Email", "Call")
println(tasks.isEmpty())      // false
println(tasks.isNotEmpty())   // true

For numeric lists, you can quickly calculate common statistics:

val scores = listOf(85, 92, 78, 95)
println(scores.sum())      // 350
println(scores.average())  // 87.5
println(scores.max())      // 95
println(scores.min())      // 78

To find an element's position, use indexOf(). It returns the index of the first occurrence, or -1 if the element isn't found:

val colors = listOf("Red", "Green", "Blue", "Green")
println(colors.indexOf("Green"))   // 1
println(colors.indexOf("Yellow"))  // -1

You can also reverse a list or sort it:

val numbers = listOf(3, 1, 4, 1, 5)
println(numbers.reversed())  // [5, 1, 4, 1, 3]
println(numbers.sorted())    // [1, 1, 3, 4, 5]

These methods return new lists and don't modify the original, making them safe to use anywhere.

challenge icon

Challenge

Medium

You are provided with the following list:

val temperatures = listOf(72, 85, 90, 68, 75, 88, 92, 70)

Using list methods, print the following information on separate lines in this exact order:

  1. The sum of all temperatures
  2. The average temperature
  3. The highest temperature
  4. The lowest temperature
  5. The index of 90 in the list
  6. The list sorted in ascending order

Try it yourself

fun main() {
    val temperatures = listOf(72, 85, 90, 68, 75, 88, 92, 70)
    
    // TODO: Write your code below
    // Use list methods to calculate and print:
    // 1. The sum of all temperatures
    // 2. The average temperature
    // 3. The highest temperature
    // 4. The lowest temperature
    // 5. The index of 90 in the list
    // 6. The list sorted in ascending order
    
}
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