2
$\begingroup$

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}

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

4 Answers 4

5
$\begingroup$

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!

$\endgroup$
3
$\begingroup$
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.

$\endgroup$
3
$\begingroup$
MapAt[0 &, lst, 2;;4]

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

Original Answer

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

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}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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