Let's try a fancy fold.
FoldPairList[{If[First@#1 === #2, True, False], Rest@#1} &, list1, list2]
(* {False, True, True, True, False} *)
It's important that list2 is no longer than list1. To guard against that, we could try
FoldPairList[Switch[#1, {}, {False, {}}, {__}, {First@#1 === #2, Rest@#1}] &, list1, list2]
(* {False, True, True, True, False} *)
which works in the other order
FoldPairList[Switch[#1, {}, {False, {}}, {__}, {First@#1 === #2, Rest@#1}] &, list2, list1]
(* {False, True, True, True, False, False} *)
We can use this in conjunction with Pick.
Pick[
list1,
FoldPairList[Switch[#1, {}, {False, {}}, {__}, {First@#1 === #2, Rest@#1}] &, list2, list1]]
(* {b, a, f} *)
or
Pick[
list2,
FoldPairList[Switch[#1, {}, {False, {}}, {__}, {First@#1 === #2, Rest@#1}] &, list1, list2]]
(* {b, a, f} *)
list2 = {c,b,bbb,f,g}? – xzczd Sep 30 '22 at 17:27{a, b, a, f}and{x, r, b, a, f}return{b, a, f}or nothing (because they're not in the same spots). What about{a, b, c, d}and{a, x, c, y}? Should this return{a,c}? Or do the elements need to be consecutive? Etc. A few more test cases would be useful. – march Sep 30 '22 at 19:06