I have a list:

b = ConstantArray[1, 50];

And I would like to replace every say 5th element with 2: I came up with:

b[[;; ;; 5]] = b[[;; ;; 5]] /. {1 -> 2}

which works, but I do not like it much since it is very unflexible and simply ugly (repeating b[[;; ;; 5]]).

I was trying to make this work with ReplacePart but I am not sure how, I tried as per manual way to replace every even'th element:

ReplacePart[b, _?Mod[i_, 5]-> 2]

and also

ReplacePart[b, _?Mod[#, 5]&-> 2]

but they do not work. Any suggestions on that?

  • 8
    $\begingroup$ What's wrong with b[[;; ;; 5]] = 2? It is the fasted method that you will find. $\endgroup$ – Henrik Schumacher Apr 12 '19 at 15:47
  • $\begingroup$ @HenrikSchumacher Oh this is the way to avoid repetition... Thank you. Otherwise it is not very flexible as to setting the rules on which positions to replace (if the rule is more complicated, it will not work) $\endgroup$ – leosenko Apr 12 '19 at 15:50
  • 3
    $\begingroup$ Your ReplacePart does not work because the syntax of the patterntest is incorrect. Try: ReplacePart[b, _?(Mod[#, 5] == 0 &) -> 2]. Part assignment is generally faster for full arrays, though. $\endgroup$ – Sjoerd Smit Apr 12 '19 at 15:51
  • $\begingroup$ Would it make sense to partition into sets of 5 and then perform a replacement on the last element of all sets then Flatten? $\endgroup$ – kickert Apr 13 '19 at 0:38

This works, but its much slower than your method.

Table[If[Mod[i, 5] == 0, b[[i]] = 2], {i, Length[b]}]

but it might be easier to specify more complicated conditions.


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