Scala Zip Example

The zip function combines two lists into tuples. If the lists are of differing lengths, the shorter length is used. If you don’t like this behavior, the zipAll function will keep all elements, filling in specified values for the blanks (compare this to the recycling rule in R, which lets you continuously cycle through the shorter list).

val arr1 = List("a", "b", "c")
val arr2 = List(1, 2, 3)

arr1.zip(arr2)

The result is tuples of each:

res2: List[(String, Int)] = List((a,1), (b,2), (c,3))

If you make a longer array, you get tuples with a length at the shortest of the two:

var arr3 = List(4, 5, 6, 7)
arr1.zip(arr3)
res3: List[(String, Int)] = List((a,4), (b,5), (c,6))

This also applies if you use a shorter array:

var arr4 = List(4, 5)
arr1.zip(arr4)

Result:

res5: List[(String, Int)] = List((a,4), (b,5))

If you don’t like this behavior, consider using zipAll.

Leave a Reply

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