How to do a list partition with offset, overhang, and cyclical padding?

a = {1, 2, 3, 4, 5, 6, 7, 8, 9};

The command

Partition[a, 2]

just partitions the input into as many nonoverlapping pairs as possible:

{{1, 2}, {3, 4}, {5, 6}, {7, 8}}

The three-argument version creates pairs with an offset of `1:

Partition[a, 2, 1]

{{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}, {7, 8}, {8, 9}}

That is already very close to what you want!

In order to pair also the last element with the first, use the four argument version of Partition to make it cycle

Partition[a, 2, 1, {1, 1}]

{{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}, {7, 8}, {8, 9}, {9, 1}}

whose shorter version is

Partition[a, 2, 1, 1]

In the usage notes of Partition (?Partition), this is somewhat hidden. The notes state (highlighting by me):

Partition[list,n,d,{Subscript[k, L],Subscript[k, R]}] specifies that the first element of list should appear at position Subscript[k, L] in the first sublist, and the last element of list should appear at or after position Subscript[k, R] in the last sublist. If additional elements are needed, Partition fills them in by treating list as cyclic.


For the specific case you can also use

lst = Range[9];
Transpose[{lst, RotateLeft[lst]}]

{{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}, {7, 8}, {8, 9}, {9, 1}}

which is the same result Partition[lst, 2, 1, 1] gives.


I propose you another option that works similarly to Partition[list,n,d,{Subscript[k, L],Subscript[k, R]}] but making use of other list-manipulation functions that might be useful in other contexts.

a = {1, 2, 3, 4, 5, 6, 7, 8, 9};
Partition[Riffle[a, RotateLeft[a, 1]], 2]