Kotlin List indices
Syntax & Examples


Syntax of List.indices

The syntax of List.indices extension property is:

val Collection<*>.indices: IntRange

This indices extension property of List returns an IntRange of the valid indices for this collection.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the characters 'a', 'p', 'p', 'l', 'e'.
  • We access the indices of list1 using the indices property, which returns an IntRange representing the valid indices for the list.
  • We store the indices in a variable named indices.
  • Finally, we print the indices to standard output using println.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(&quot;a&quot;, &quot;p&quot;, &quot;p&quot;, &quot;l&quot;, &quot;e&quot;);
    val indices = list1.indices;
    println(indices);
}

Output

0..4

2 Example

In this example,

  • We create a list named list1 containing the integers 10, 20, 30.
  • We access the indices of list1 using the indices property, which returns an IntRange representing the valid indices for the list.
  • We store the indices in a variable named indices.
  • Finally, we print the indices to standard output using println.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(10, 20, 30);
    val indices = list1.indices;
    println(indices);
}

Output

0..2

3 Example

In this example,

  • We create a list named list1 containing the integers 10, 20, 30.
  • We create a sub-list of list1 using the subList function, containing elements at indices 1 and 2.
  • We access the indices of the sub-list using the indices property, which returns an IntRange representing the valid indices for the sub-list.
  • We store the indices in a variable named indices.
  • Finally, we print the indices to standard output using println.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(10, 20, 30);
    val indices = list1.subList(1, 3).indices;
    println(indices);
}

Output

0..1

Summary

In this Kotlin tutorial, we learned about indices extension property of List: the syntax and few working examples with output and detailed explanation for each example.