Is there a Scala equivalent for the python enumerate?

Viewed 11728

I'd like the convienience of

for i, line in enumerate(open(sys.argv[1])):
  print i, line

when doing the following in Scala

for (line <- Source.fromFile(args(0)).getLines()) {
  println(line)
}
2 Answers

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

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

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

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

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

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

Related