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?
There is a forEachIndexed function in the standard library:
forEachIndexed
myList.forEachIndexed { i, element -> println(i) println(element) }
See the @ s1m0nw1 answer , and withIndex is also a great way to iterate through Iterable .
withIndex
Iterable
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:
for
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.:
indices
Collection
Array
for(i in ints.indices){ println("$i: ${ints[i]}") }