Does Kotlin have an "enumeration" function like Python?

In Python, I can write:

for i, element in enumerate(my_list): print i # the index, starting from 0 print element # the list-element 

How can I write this in Kotlin?

+7
list kotlin enumerate
source share
2 answers

There is a forEachIndexed function in the standard library:

 myList.forEachIndexed { i, element -> println(i) println(element) } 

See the @ s1m0nw1 answer , and withIndex is also a great way to iterate through Iterable .

+14
source share

Iterations in Kotlin: some alternatives

  • As already said, forEachIndexed is one way to do it.

  • I want to point out an alternative: the withIndex extension defined for Iterable types can be used in for -each:

     val ints = arrayListOf(1, 2, 3, 4, 5) for ((i, e) in ints.withIndex()) { println("$i: $e") } 
  • Then there is the indices extension property available for Collection , Array , etc., which approximates the general for , as is known from C, Java, etc.:

     for(i in ints.indices){ println("$i: ${ints[i]}") } 
+15
source share

All Articles