# Built-in singles-to-pairs ({a, b, c, d} -> {{a, b}, {b, c}, {c, d}})? [closed]

This all the time: an often-recurring coding pattern that is just tedious enough to type and/or just opaque enough, that one feels it should be encapsulated into a function, but at the same time, the amount of code this would require is just too small to warrant creating a package for it (so that one can, in fact, re-use it in the future).

So one just tosses the function in some Misc or Etc package.

Unless, of course, Mathematica already has such a function.

In this case, the pattern-abstracting function would be

singlesToPairs[list_List] := Transpose @ {Drop[list, -1], Drop[list, 1]}


E.g.

singlesToPairs[Range[5]]
(* {{1, 2}, {2, 3}, {3, 4}, {4, 5}} *)


Does Mathematica already have something like this?

• Yes it does, Partition[Range[5], 2, 1]. – C. E. Mar 29 '17 at 16:41

as mentioned by C.E. the preferred built-in function is:

Partition[Range[5], 2, 1]

(* {{1, 2}, {2, 3}, {3, 4}, {4, 5}} *)


as pointed out by Simon Woods:

SequenceCases[Range[5], {_, _}, Overlaps -> True]
(* {{1, 2}, {2, 3}, {3, 4}, {4, 5}} *)


one can also use ReplaceList

ReplaceList[Range[5], {___, a_, b_, ___} :> {a, b}]
(* {{1, 2}, {2, 3}, {3, 4}, {4, 5}} *)


and like your user defined way one can also do it using ReplaceAll in a recursive manner

func[{x_Integer}] := {};
func[x_] := x /. {a_, q_, r___} :> Join[{{a, q}}, func[{q, r}]]

func[Range@5]
(* {{1, 2}, {2, 3}, {3, 4}, {4, 5}} *)


another way

Thread[{Most@#,Rest@#}]&@Range[5]
(* {{1, 2}, {2, 3}, {3, 4}, {4, 5}} *)

• You could also use SequenceCases[Range[5], {_, _}, Overlaps -> True] – Simon Woods Mar 29 '17 at 18:09
• @SimonWoods thanks for pointing it out. incorporating your solution. – Ali Hashmi Mar 29 '17 at 19:43