7
$\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
  • 3
    $\begingroup$ Partition[list, 2, 1, {1, 1}] $\endgroup$
    – thorimur
    Apr 15, 2021 at 21:54
  • 3
    $\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, 2021 at 21:56
  • $\begingroup$ @thorimur I really appreciate the explanation. Thanks $\endgroup$
    – geoffrey
    Apr 19, 2021 at 13:48

6 Answers 6

8
$\begingroup$
list={1,2,3,4};

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

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

$\endgroup$
5
$\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$
5
$\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, 2021 at 3:35
4
$\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$
2
$\begingroup$
list = {1, 2, 3, 4};

Using SequenceCases

SequenceCases[list /. {a_, b__} -> {a, b, a}, {_, _}, Overlaps->All]

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

$\endgroup$
2
$\begingroup$
list = {1, 2, 3, 4};

Using MovingMap:

RotateLeft@MovingMap[# &, list, 1, 4]

(*{{1, 2}, {2, 3}, {3, 4}, {4, 1}}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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