Use replacePart from an element n to an element m of a list

I would like to replace a part of a list from an element n to an element m by zeros. I believe the function ReplacePart could be useful

Example: I want to replace elements from 2 to 4 by zeros :

INPUT : {1,2,3,4,5}

OUTPUT : {1,0,0,0,5}

• If your input is called l1 then l1[[2;;4]]=0 will modify the list as you wish. Is that the answer you want? Sep 6, 2021 at 15:39
• Yes thank you, I didn't expected that to be that simple . Sep 6, 2021 at 15:46
• Be aware that the solution offered by @HighPerformanceMark will change the value of l1, but ReplacePart[l1, Transpose@{Range[2, 4]} -> 0] will not.
– Alan
Sep 6, 2021 at 16:19

Try this:

lst = {1, 2, 3, 4, 5};
ReplacePart[lst, Range[2, 4] /. x_?NumberQ -> Rule[x, 0]]

(*   {1, 0, 0, 0, 5}   *)


Have fun!

alist = {1, 2, 3, 4, 5}
ReplacePart[alist, (i_ /; 1 < i < 5) -> 0]


{1, 0, 0, 0, 5}

or

   alist = ReplacePart[alist, (i_ /; 1 < i < 5) -> 0]


if you want to modify alist itself.

MapAt[0 &, lst, 2;;4]

(* {1, 0, 0, 0, 5} *)


SubsetMap[0 #&, lst, Range[2,4]]
(* {1, 0, 0, 0, 5} *)


I am assuming that continuous values need to be filtered.

alist = {1, 2, 3, 4, 5}
alist /. x_ /; x >= 2 && x <= 4 -> 0


{1, 0, 0, 0, 5}

If you want to filter just integers, consider the following.

blist = {1, 2, 2.2, 3, 3.2, 4, 4.4, 5, 6}

blist /. x_Integer /; x >= 2 && x <= 4 -> 0


{1, 0, 2.2, 0, 3.2, 0, 4.4, 5, 6}

-------------- Apply the continuous version on blist

blist /. x_ /; x >= 2 && x <= 4 -> 0

{1, 0, 0, 0, 0, 0, 4.4, 5, 6}


------------- or is it list elements at index 2 through to 4 that you need to zero out?

ReplacePart[alist, {{2}, {3}, {4}} -> 0]


{1, 0, 0, 0, 5}