I have a list with n occurrences of a certain element. I have a second list with

 Length[lis2] = n

I would like to replace the nth occurrence of the certain element in lis1 with the nth member of lis2.

lis1 = {A,b,c,d,A,e,f,g} Here, A is the special character.
lis2 = {X,Y}

res = {X,b,c,d,Y,e,f,g}

It seems that there should be an easy way of placing the nth member of lis2 at the right place in lis1 using


Thanks for any ideas!

  • 1
    $\begingroup$ ReplacePart[lis1, Thread[Flatten[Position[lis1, A]][[;; UpTo@Length@lis2]] -> lis2]] will get you started. You'll want to harden this with error checking (enough elements to change, etc) if this is not some one-shot need. $\endgroup$
    – ciao
    Sep 20, 2019 at 6:07

2 Answers 2

lis1 = {A, b, c, d, A, e, f, g}
lis2 = {X, Y};

pos = Flatten @ Position[lis1, A];
lis1[[pos]] = lis2[[;; UpTo @ Length @ pos]];

{X, b, c, d, Y, e, f, g}

You can also use ReplaceAll as follows:

lis1 = {A, b, c, d, A, e, f, g};

l = RotateLeft[lis2];
lis1 /. A :> First[l = RotateRight[l]]

{X, b, c, d, Y, e, f, g}

l = RotateLeft[lis2];
lis1 /. e :> First[l = RotateRight[l]]

{A, b, c, d, A, X, f, g}


This one does seem to do the trick:

ReplacePart[lis1, Position[lis1, A][[All, 1]] -> lis2]

I assume that all your inputs have proper length and structure. If thats not guaranteed you might want to incorporate some input checks or use different method altogether.


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.