10
$\begingroup$

I want to swap the list to make a new list as follows. The code works but I'm wondering if there is a neat code, or an elegant way to do this.

list = {1, -1, -1, 1, 0, 0, d, -1, 1};
newlist = {Sequence @@ list[[4 ;; 6]], Sequence @@ list[[1 ;; 3]],
Sequence @@ list[[7 ;; 9]]}
$\endgroup$
5
  • 4
    $\begingroup$ list[[#]] & /@ {4 ;; 6, 1 ;; 3, 7 ;; 9} // Flatten $\endgroup$
    – LouisB
    Apr 9, 2021 at 8:42
  • $\begingroup$ Are you concerned about computational efficiency for very long lists? $\endgroup$
    – A.G.
    Apr 9, 2021 at 14:26
  • $\begingroup$ @A.G. that would be good too. What I had in mind was to make it short and easy to understand. $\endgroup$
    – emnha
    Apr 9, 2021 at 14:42
  • $\begingroup$ Then permutations are probably better, in order to avoid duplicating the list. $\endgroup$
    – A.G.
    Apr 9, 2021 at 19:10
  • $\begingroup$ Should this go on Stack Overflow? $\endgroup$ Apr 9, 2021 at 19:28

5 Answers 5

14
$\begingroup$

Permute exists for reordering lists.

Permute[list, Cycles[{{1, 4}, {2, 5}, {3, 6}}]]

This swaps entries $1 \leftrightarrow 4$, $2 \leftrightarrow 5$ and $3 \leftrightarrow 6$.

The necessary permutation can be found using FindPermutation:

FindPermutation[Range@9, {4, 5, 6, 1, 2, 3, 7, 8, 9}] 

Cycles[{{1, 4}, {2, 5}, {3, 6}}]

$\endgroup$
1
  • 9
    $\begingroup$ list[[{4, 5, 6, 1, 2, 3, 7, 8, 9}]] works too. $\endgroup$
    – andre314
    Apr 9, 2021 at 10:35
9
$\begingroup$

At least shorter:

Flatten@Partition[list, 3][[{2, 1, 3}]]
$\endgroup$
9
$\begingroup$

Id suggest using TakeList

TakeList[ist, {{4, 6}, 3, All}]
TakeList[ist, {{4, 6}, {1, 3}, {1, 3}}]

The indices need to be relative to those elements that are not yet taken.

If you have absolute indices given:

ist = Range[20];
parts = {{5, 6}, {9, 13}, {1, 4}, {19, 20}, {14, 18}};

Catenate[ist[[# ;; #2]] & @@@ parts]
$\endgroup$
3
$\begingroup$
list = Range[9];
swap =  {{2, 5}, {3, 6}};

Fold[SubsetMap[RotateRight, #1, #2] &, list, swap]

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

$\endgroup$
3
$\begingroup$
list = Range[9];
swap = {{2, 5}, {3, 6}};

ds = CreateDataStructure["LinkedList"];

Scan[ds["Append", #] &, list];

ds["SwapPart", ##] & @@@ swap;

Normal @ ds

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

ds["Visualization"]

enter image description here

Guide to Data Structures

$\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.