CodeBlanks Logo Icon CodeBlanks

zip and unzip

Learn combining with zip and unzip.

zip and unzip

zip merges two collections in parallel; each element becomes a Pair. unzip splits a list of Pairs into two lists.

Example: listOf("a", "b").zip(listOf(1, 2)) returns [(a, 1), (b, 2)]. listOf("a" to 1, "b" to 2).unzip() gives ([a, b], [1, 2]). zip merges up to the shorter list's size.

Transform with zip

Passing a lambda to zip transforms each pair. This is a concise way to relate two lists and produce a single list.

Example: listOf("a", "b").zip(listOf(1, 2)) { s, n -> "$s$n" }. This returns ["a1", "b2"]. The lambda takes two parameters: elements from the first and second list. This pattern is useful for joining label-value pairs.

Practice Merge label and value with zip

In main assign the result of listOf("a", "b", "c").zip(listOf(1, 2, 3)) { s, n -> "$s=$n" } to a variable and print it with println.

Starter code

Main.kt
// in main merge two lists with zip
// turn each pair into s=n and print

Sample solution

Main.kt
fun main() {
    val pairs = listOf("a", "b", "c").zip(listOf(1, 2, 3)) { s, n -> "$s=$n" }
    println(pairs)
}

Expected output

[a=1, b=2, c=3]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the zip/unzip parts

Term Meaning
zip Parallel merge
unzip Split into two lists
Pair Element pair
(a, 1) Result pair

2 How many elements does listOf("a", "b").zip(listOf(1, 2, 3)) return?

  • 1
  • 5
  • 3
  • 2 Correct answer

Explanation: zip merges up to the shorter list's size.

3 Complete the unzip call

Question
val (letters, nums) = listOf("a" to 1, "b" to 2).____()
Answer
val (letters, nums) = listOf("a" to 1, "b" to 2).unzip()

Explanation: unzip splits a Pair list into two lists.

All lessons in Advanced