[ACCEPTED]-Is there a Scala equivalent for the python enumerate?-enumerate

Accepted answer
Score: 56

You can use the zipWithIndex from Iterable trait:

for ((line, i) <- Source.fromFile(args(0)).getLines().zipWithIndex) {
   println(i, line)
}

0

Score: 10

As already answered by others, if you want 8 your index to start from 0, you can use 7 zipWithIndex:

for ((elem, i) <- collection.zipWithIndex) {
    println(i, elem)
}

Because zipWithIndex creates a copy of the collection 6 if called on the collection itself, you 5 may want to call it to a view of the colleciton 4 instead: collection.view.zipWithIndex.

Nonetheless, Python's enumerate has an 3 optional parameter to set the start value 2 of your index. In scala, you can do:

for ((elem, i) <- collection.zip(Stream from 1) {
    println(i, elem)
}

For 1 a longer discussion, read https://alvinalexander.com/scala/how-to-use-zipwithindex-create-for-loop-counters-scala-cookbook.

More Related questions