I have a list and need to remove certain members of the list.

lis = {f1,a,b,c,d,f2,e,g,h,i,f1,j,k,l,m,f2,n,o}

I need to remove each occurrence of f1 and the following two elements, and remove each occurrence of f2 and the following element. (f1 and f2 will always at least two elements apart). This gives:

res = {c,d,g,h,i,l,m,o}

ReplaceList would seem to be useful, but I am not able to see it. Thanks for any suggestions.


2 Answers 2



SequenceReplace[{f1, _, _} | {f2, _} -> Nothing] @ lis
{c, d, g, h, i, l, m, o}

Split+ ReplaceAll

ReplaceAll[{{f1, _, _, a___} | {f2, _, a___} :> a}] @
 Split[lis, #2 =!= f1 && #2 =!= f2 &]
{c, d, g, h, i, l, m, o}
  • $\begingroup$ This does not match res = {c,d,g,h,i,l,m,o}; but i could simply delete each occurrence of f1 and f2 to get res. Thanks @kglr! $\endgroup$
    – Suite401
    Oct 17, 2020 at 23:40
  • $\begingroup$ @Suite401, fixed it. $\endgroup$
    – kglr
    Oct 17, 2020 at 23:49
lis = {f1, a, b, c, d, f2, e, g, h, i, f1, j, k, l, m, f2, n, o};

An alternative is to use SequenceSplit and DeleteCases:

patt = {f1, _, _} | {f2, _};

Flatten[DeleteCases[SequenceSplit[lis, s : patt :> s], patt]]

(*{c, d, g, h, i, l, m, o}*)

Or using SequenceSplit and Cases:

Cases[s : Except[patt] :> Splice@s]@SequenceSplit[lis, s : patt :> s]

(*{c, d, g, h, i, l, m, o}*)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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