# Functional realisation of do-loop

I'm currently optimising my code and I'm using a lot of loops, so I was wondering if there is a smarter or faster way to do things like:

 Do[If[MemberQ[List1[[II]], List2_], AppendTo[Newlist1, List1[[II]]]], {II, Length[List1]}]

I guess using Apply would be better, but since I'm not primary a programmer I would be happy for any help. Thank you!

• newlist = Intersection[list1,list2] would do this. Sorts the elements in the results, though; see here. In general it is a good idea to use builtin functions instead of "rolling your own". Dec 29, 2020 at 14:26
• List2_ should not have _ after it. That's supposed to be for arguments and patterns. You don't need to use [[ ]]. You can write Do loops like this for example: Do[Print[x]; , {x, {"a", "b", "c"}}] and the x will take the value in the list on each iteration. Finally, don't use AppendTo, use Reap and Sow instead. Dec 29, 2020 at 14:28
• @Hausdorff AppendTo is not good, better to use something like newlist = Select[list1, MemberQ[list2, #] &]. See here for a discussion. Dec 29, 2020 at 14:30
• I really like the last one @Roman , how would I do that if list1is a product e.g. list1 = {abcd,...,...} and list2={a,r,l,m}. I would like to extract elements of list1 if elements there contain elements of list2. Dec 29, 2020 at 15:16

First question: select those elements in list1 that also appear in list2:

list1 = {a, b, c, d, e, f};
list2 = {e, g, i};
Select[list1, MemberQ[list2, #] &]
(*    {e}    *)


Second question: select those elements in list1 that have a factor that is in list2:

list1 = {a b c d, x y z, m n o};
list2 = {a, r, l, m};
Select[list1, IntersectingQ[List @@ #, list2] &]
(*    {a b c d, m n o}    *)


Try the following, first remove from the first list the elements of the second one:

lst1 = {a, b, c, d, e, f, g};
lst2 = {b, c, g};
Complement[lst1, lst2]
(*  {a, d, e, f}  *)


and then append it to the newList.

Clear[newList];
newList = {AA, BB, CC}; (*This is the initial newList*)
AppendTo[newList, Complement[lst1, lst2]] // Flatten
(*  {AA, BB, CC, a, d, e, f}   *)


Have fun!

• Join might be better than AppendTo and Flatten. Dec 29, 2020 at 21:19

Question 1

la = {a, b, c, d, e, f};
lb = {e, g, i};

Cases[la, Alternatives @@ lb]


{e}

Question 2 (see comment)

la = {a b c d, x y z, m n o};
lb = {a, r, l, m};

Pick[la, ContainsAny[#, lb] & /@ List @@@ la]


{a b c d, m n o}

Question 1

la = {a, b, c, d, e, f};
lb = {e, g, i};

DeleteCases[la, Alternatives @@ Union @@ UniqueElements[{la, lb}]]


{e}

Question 2

la = {a b c d, x y z, m n o};
lb = {a, r, l, m};

DeleteCases[la, x_ /; DisjointQ[List @@ x, lb]]


{a b c d, m n o}