3
$\begingroup$

I have a list (for example) $\{1,2,3,4\}$. I want a list $\{\{1,2\},\{2,3\},\{3,4\},\{4,1\}\}$ where only the elements that are "cyclically adjacent" in the input list are in the output list.

$\endgroup$
3
  • 1
    $\begingroup$ Partition[list, 2, 1, {1, 1}] $\endgroup$ – thorimur Apr 15 at 21:54
  • 2
    $\begingroup$ This uses the extra of arguments of Partition to (in order): make lists of length 2, such that each list begins 1 after the start of the previous one, and such that the {first, last} elements of the result are the elements appearing at {1,1} of list (i.e. it both starts and ends with the first element of the list) $\endgroup$ – thorimur Apr 15 at 21:56
  • $\begingroup$ @thorimur I really appreciate the explanation. Thanks $\endgroup$ – geoffrey Apr 19 at 13:48
7
$\begingroup$
list={1,2,3,4};

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

{{1, 2}, {2, 3}, {3, 4}, {4, 1}}

$\endgroup$
3
$\begingroup$

There are many ways to do this. Another is

lis = {1, 2, 3, 4}
MapThread[List, {RotateRight[lis], lis}]

Mathematica graphics

If you want the order the same as you show, then do

 Sort[MapThread[List, {RotateRight[lis], lis}]]

Mathematica graphics

$\endgroup$
3
$\begingroup$

Or first, change the list, then Partition.

{1, 2, 3, 4} // Join[#, {First@#}] & // Partition[#, 2, 1] &
$\endgroup$
1
  • $\begingroup$ Partition[{1, 2, 3, 4}, 2, 1, 1] $\endgroup$ – expression Apr 16 at 3:35
2
$\begingroup$
list = {1, 2, 3, 4};

Transpose[{#, RotateLeft @ #}] & @ list
{{1, 2}, {2, 3}, {3, 4}, {4, 1}}

Also

Partition[Riffle[#, RotateLeft @ #], 2] & @ list
{{1, 2}, {2, 3}, {3, 4}, {4, 1}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.