Kotlin

zip and zipWithIndex

admin by @admin ADMIN
Jun 14, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`zip` pairs elements positionally; the result is the length of the shorter list. `withIndex()` gives you `(index, value)` pairs without the manual `forEachIndexed`.
Kotlin
Raw
fun main() {
    val names = listOf("Alice", "Bob", "Cara")
    val ages  = listOf(30, 25, 35, 40)        // longer — extras get dropped

    val pairs = names.zip(ages)
    println(pairs)                              // [(Alice, 30), (Bob, 25), (Cara, 35)]

    // Zip with a transform
    val rows = names.zip(ages) { name, age -> "$name is $age" }
    println(rows)

    // Reverse: unzip a List<Pair> → Pair<List, List>
    val (n, a) = pairs.unzip()
    println("names=$n  ages=$a")

    // withIndex — like enumerate() in Python
    for ((i, name) in names.withIndex()) {
        println("$i: $name")
    }

    // Iterate two lists positionally with their indices
    for ((i, pair) in pairs.withIndex()) {
        val (name, age) = pair
        println("$i: $name=$age")
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.