Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Kotlin have an "enumerate" 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?

like image 679
fafl Avatar asked Oct 19 '17 08:10

fafl


2 Answers

Iterations in Kotlin: Some Alternatives

Like already said, forEachIndexed is a good way to iterate.

Alternative 1

The extension function withIndex, 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")
}

Alternative 2

The extension property indices is available for Collection, Array etc., which let's you iterate like in a common for loop as known from C, Java etc:

for(i in ints.indices){
     println("$i: ${ints[i]}")
}
like image 127
s1m0nw1 Avatar answered Nov 17 '22 03:11

s1m0nw1


There is a forEachIndexed function in the standard library:

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

See @s1m0nw1's answer as well, withIndex is also a really nice way to iterate through an Iterable.

like image 29
zsmb13 Avatar answered Nov 17 '22 03:11

zsmb13