scala – List – zip , unzip

The zip operation takes two lists and forms a list of pairs:

If the two lists are of different length, any unmatched elements are dropped:

 

A useful special case is to zip a list with its index. This is done most efficiently with the zipWithIndex method, which pairs every element of a list with the position where it appears in the list.

Any list of tuples can also be changed back to a tuple of lists by using the unzip method:

object List_Zip_Unzip extends App {

//  If the two lists are of different length, any unmatched elements are dropped:

  val lst=List('a','b','c')

  val lstzip=lst.indices zip lst
  println(lstzip)
  //scala.collection.immutable.IndexedSeq[(Int, Char)] 

  val lstindex=lst.zipWithIndex
  println(lstindex)
// List[(Char, Int)] 

println(lstindex.unzip)

}


Vector((0,a), (1,b), (2,c))
List((a,0), (b,1), (c,2))
(List(a, b, c),List(0, 1, 2))

Leave a comment