Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 44 / 68

Pairing Up Two Lists (the zip operation)

In this lesson you will learn to pair up two lists with zip in Kotlin, so related data can be handled together. This is for anyone searching for "Kotlin zip how to use".

Combining two corresponding lists - a list of names and a list of scores, say - into pairs one by one is called a zip operation. Kotlin has a method named exactly that: .zip().

The sample code combines the elements at matching positions in names and scores with names.zip(scores) and returns them as a list of Pair. Notice how a single line produces the whole list of pairs.

A common stumbling block for beginners is what happens when the two lists are different lengths. .zip() stops at the shorter one, so any leftovers are simply not included.

In real-world development it is also a frequent choice when you want to loop over several lists at once.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)