0
0
KotlinHow-ToBeginner · 3 min read

How to Zip Lists in Kotlin: Simple Guide with Examples

In Kotlin, you can zip two lists using the zip() function, which pairs elements from both lists into a list of Pair objects. This function stops when the shortest list ends, creating pairs of corresponding elements.
📐

Syntax

The zip() function combines two lists into a list of pairs. Each pair contains one element from each list at the same position.

Syntax:

val zippedList = list1.zip(list2)

Here, list1 and list2 are the lists you want to combine. The result is a list of Pair<T, R> where T and R are the types of elements in the two lists.

kotlin
val list1 = listOf("a", "b", "c")
val list2 = listOf(1, 2, 3)
val zippedList = list1.zip(list2)
println(zippedList)
Output
[(a, 1), (b, 2), (c, 3)]
💻

Example

This example shows how to zip two lists of different types and print the resulting pairs.

kotlin
fun main() {
    val fruits = listOf("Apple", "Banana", "Cherry")
    val prices = listOf(100, 200, 300)

    val fruitPrices = fruits.zip(prices)

    for ((fruit, price) in fruitPrices) {
        println("$fruit costs $price dollars")
    }
}
Output
Apple costs 100 dollars Banana costs 200 dollars Cherry costs 300 dollars
⚠️

Common Pitfalls

One common mistake is expecting zip() to combine all elements when lists have different lengths. zip() stops at the shortest list's length, so extra elements in the longer list are ignored.

Another pitfall is not realizing the result is a list of Pair objects, so you need to access first and second or use destructuring.

kotlin
fun main() {
    val listA = listOf("x", "y", "z", "extra")
    val listB = listOf(1, 2, 3)

    // Wrong: expecting all elements combined
    val zipped = listA.zip(listB)
    println(zipped) // Output: [(x, 1), (y, 2), (z, 3)] - 'extra' is ignored

    // Correct: handle different lengths consciously
    println("Zipped size: ${zipped.size}")
}
Output
[(x, 1), (y, 2), (z, 3)] Zipped size: 3
📊

Quick Reference

Tips for using zip() in Kotlin:

  • Stops at shortest list: Extra elements in longer lists are ignored.
  • Result type: List of Pair objects.
  • Destructuring: Use for ((a, b) in zippedList) to access pairs easily.
  • Custom transform: Use zip(other) { a, b -> ... } to create custom results.

Key Takeaways

Use zip() to combine two lists into pairs element-wise.
zip() stops at the shortest list length, ignoring extra elements.
The result is a list of Pair objects, accessible via destructuring.
You can provide a custom transform function to zip() for different output.
Always handle lists of different sizes carefully to avoid unexpected results.