# Replace multiple elements at different positions

I have a list a = {0, 0, 0, 0, 0}; and now I would like to make only those elements 100 at the positions in pu = {1,4,5}; So I would like to get {100,0,0,100,100} ReplacePart[a, pu -> 100], doesn't show the right result unfortunately. Could anybody help me to solve this?

Thank you in advance! Carlijn Bakker

• Try with Thread[pu -> 100] or Transpose[{pu}] -> 100. Dec 16, 2016 at 9:30

You can also use lists with Part or [[ ]]

a = {0, 0, 0, 0, 0};
a[[{1, 3}]] = 7;
a
pu = {1, 4, 5};
a[[pu]] = 100;
a


{7, 0, 7, 0, 0}

{100, 0, 7, 100, 100}

• Thank you so much for the solution and the quick respons!! Dec 16, 2016 at 9:56
• No worries :D Since you are new, dont forget to accept an answer if it solved your problem, that is useful for every body. Dec 16, 2016 at 9:58
• Okay great! I'll do that, thanks for the help! Dec 16, 2016 at 10:26

Re: ReplacePart[a, pu -> 100], doesn't show the right result unfortunately:

You can use List/@pu -> 100 instead of pu -> 100

a = {0, 0, 0, 0, 0}; pu = {1, 4, 5};

ReplacePart[a, List /@ pu -> 100]


{100, 0, 0, 100, 100}

You can also use MapAt:

MapAt[100 &, a, List /@ pu]


{100, 0, 0, 100, 100}

a = {0, 0, 0, 0, 0};

p = {1, 4, 5};


Using ReplaceAt (new in 13.1)

f = ReplaceAt[_ :> 100, List /@ p];

f @ a


{100, 0, 0, 100, 100}

With ApplyTo (new in 12.2) we can change a inline (like in the accepted answer)

a //= f;

a


{100, 0, 0, 100, 100}

ReplaceAt has the advantage that we can easily impose conditions

a = {0, Missing[], 0, 0, 0};

p = {1, 4, 5};

ReplaceAt[_?NumberQ :> 100, List /@ p] @ a


{100, Missing[], 0, 100, 100}

a = {0, 0, 0, 0, 0};

p = {1, 4, 5};


Using SubsetMap:

SubsetMap[100 + # &, a, p]

(*{100, 0, 0, 100, 100}*)

• One of my favourite functions cleverly employed :)
– eldo
Feb 24 at 13:17
• Thanks, @eldo! It's also one of my favorite functions ;) Feb 24 at 13:22