Scala unzip example

The unzip takes a sequence of tuples, and gives you two lists made from the values in the tuples.

To make this simple to see, we’ll make a list, and then do zipWithIndex:

List("a", "b", "c")
res30: List[String] = List(a, b, c)

List("a", "b", "c").zipWithIndex
res31: List[(String, Int)] = List((a,0), (b,1), (c,2))

The result list has three tuples, with our original list values and the index.

If we just add “unzip”, we’ll get the list data back:

List("a", "b", "c").zipWithIndex.unzip

res32: (List[String], List[Int]) = 
  (List(a, b, c),List(0, 1, 2))

To get this in a form you’d actually want, you can just un-tuple it, and you’ll get the two lists you wanted originally:

var (ids, indexes) = 
  List("a", "b", "c").zipWithIndex.unzip
ids: List[String] = List(a, b, c)
indexs: List[Int] = List(0, 1, 2)

Leave a Reply

Your email address will not be published. Required fields are marked *