I am trying to split Scala list like List(1,2,3,4)
into pairs (1,2) (2,3) (3,4)
, what's a simple way to do this?
Asked
Active
Viewed 1.8k times
36

Garrett Hall
- 29,524
- 10
- 61
- 76
3 Answers
82
val xs = List(1,2,3,4)
xs zip xs.tail
// res1: List[(Int, Int)] = List((1,2), (2,3), (3,4))
As the docs say, zip
Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs. If one of the two collections is longer than the other, its remaining elements are ignored.
So List('a,'b,'c,'d)
zipped with List('x,'y,'z)
is List(('a,'x), ('b,'y), ('c,'z))
with the final 'd
of the first one ignored.
From your example, the tail
of List(1,2,3,4)
is List(2,3,4)
so you can see how these zip together in pairs.

Luigi Plinge
- 50,650
- 20
- 113
- 180
-
2This is short and clever, but it harder to understand I think. – Garrett Hall Jun 28 '12 at 17:15
-
4This would be my first choice for conciseness and clarity. Have an upvote. – Brian Jun 28 '12 at 17:21
-
1@Luigi: I upvoted this answer and much prefer it to the currently accepted one, but an explanation would be more helpful than "LOL if you think this hard to understand". – Travis Brown Jun 28 '12 at 17:56
-
Or `xs.zip(xs.drop(1))` if you're happy to have an empty List returned when `xs` is empty - otherwise you'll get an `UnsupportedOperationException` (thrown by `tail` on an empty collection) – David Aug 09 '22 at 16:42
17
To produce a list of pairs (i.e. tuples) try this
List(1,2,3,4,5).sliding(2).collect{case List(a,b) => (a,b)}.toList

Jakob Odersky
- 1,371
- 11
- 23
-
4Use `map` instead of `collect` — this will save an `isDefinedAt` call and throw an exception if all of a sudden your original collection is not a `List` any more, instead of silently producing an empty result. For this same reason, you should probably pattern-match `Seq(a,b)` instead of `List(a,b)`. – Jean-Philippe Pellet Jun 28 '12 at 16:43
10
List(1,2,3,4).sliding(2).map(x => (x.head, x.tail.head)).toList
res0: List[(Int, Int)] = List((1,2), (2,3), (3,4))

Brian
- 20,195
- 6
- 34
- 55
-
1This is the answer I came up as well when I wrote it. Seems more obvious and readable than the rest imo. – arviman Jul 25 '17 at 13:45
-
@arviman This is what I came up with at the time. I was probably trying to force the use of `sliding`. In hindsight, the accepted answer is much better. – Brian Jul 25 '17 at 13:50