1
$\begingroup$

Suppose to have a list of items and two lists of indexes that are parametric and for example are:

l={2,3,5,7,11,13,17}
i1={3,4,7}
i2={4,7,3}

I need a clever code to execute:

{l[[3]],l[[4]],l[[7]]}={l[[4]],l[[7]],l[[3]]}

so that the value of l will be:

{2,3,7,17,11,13,5}
$\endgroup$
1
  • 5
    $\begingroup$ Simply write: l[[i1]] = l[[i2]]; $\endgroup$ Mar 10 at 16:09

2 Answers 2

2
$\begingroup$
list = {2, 3, 5, 7, 11, 13, 17};

i1 = {3, 4, 7};
i2 = {4, 7, 3};

Using SubsetMap (new in 12.0)

list = SubsetMap[list[[i2]] &, list, i1]

{2, 3, 7, 17, 11, 13, 5}

Using ApplyTo (new in 12.2)

list //= SubsetMap[list[[i2]] &, i1]

{2, 3, 7, 17, 11, 13, 5}

$\endgroup$
1
$\begingroup$
list = {2, 3, 5, 7, 11, 13, 17};

i1 = {3, 4, 7};
i2 = {4, 7, 3};

Using ReplacePart:

ReplacePart[list, Thread[i1 -> list[[i2]]]]

(*{2, 3, 7, 17, 11, 13, 5}*)
$\endgroup$

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