# Searching for a list in a list

I want to see if a specific list is part of another list and get either True or False.

As an example:

list1={1,2,3,4}
list2={1,2}
list3={1,3}


list2 is now part of list1 and the argument should be True, while list3 isn't part of list1 as it is not the correct order.

I tried several Pattern Mactching Functions like MemberQ, which only works for elements not for lists. SubsetQ is pretty close, but doesn't check the correct order as well as ContainsX.

My workaround is to convert the list into a string and use StringContainsQ, but I think there might be a better solution as well.

• SequenceCases[list1, #] & /@ {list2, list3} Commented Mar 13 at 13:31
• inItQ[alist_,anotherlist_]:=MatchQ[alist,Join[{___},anotherlist,{___}]] followed by inItQ[list1,list2] and inItQ[list2,list3]
– Bill
Commented Mar 13 at 13:43
• Should llist4={2,1} give True or False? Commented Mar 13 at 15:16

a = {1, 2, 3, 4};
b = {1, 2};
c = {1, 3};


1.

Using SequenceCases

SequenceCases[a, b] == {b}


True

SequenceCases[a, c] == {c}


False

2.

Using SequenceCount

SequenceCount[a, #] > 0 & /@ {b, c}


{True, False}

3.

Using Partition

MemberQ[#] @ Partition[a, 2, 1] & /@ {b, c}


{True, False}

Partition should be significantly faster with long lists than one of the Sequence-functions

Clear[f, g]

f[alist_?VectorQ, blist_?VectorQ] :=
Subsequences[alist, {Length@blist}] // MemberQ[blist]

g = LongestCommonSubsequence[#1, #2] === #2 &;


Test:

list1 = {1, 2, 3, 4};
list2 = {1, 2};
list3 = {1, 3};
list4 = {1, 2, 3};

p = Permutations[{list1, list2, list3, list4}, {2}]

Transpose[{p, Apply[f, p, {1}]}] // Grid


Similarly: Transpose[{p, g @@@ p}] // Grid

l1 = {1, 2, 3, 4};
l2 = {1, 2};
l3 = {1, 3};


Another way using ReplaceList:

patt = PatternSequence[##] &;

f = ReplaceList[#1, {___, s : patt @@ #2, ___} :> {s}] =!= {} &;

f @@ {l1, l2}

(*True*)

f @@ {l1, l3}

(*False*)


Or using PositionIndex:

f = Det@Differences@Lookup[PositionIndex[#1], #2] == 1 &;

f @@ {l1, l2}

(*True*)

f @@ {l1, l3}

(*False*)