Test if list contains another list

gauravatnet at gmail.com gauravatnet at gmail.com
Thu Sep 18 12:24:16 CEST 2008

```On Sep 9, 9:09 pm, "J. Cliff Dyer" <j... at sdf.lonestar.org> wrote:
> On Tue, 2008-09-09 at 10:49 +0200, Bruno Desthuilliers wrote:
> > Matimus a écrit :
> > > On Sep 8, 12:32 am, Bruno Desthuilliers
> > > <bdesth.quelquech... at free.quelquepart.fr> wrote:
> > (snip)
> > >>  >>> set(a).issubset(set(b))
> > >> True
>
> > > Just to clarify, doing it using sets is not going to preserve order OR
> > > number of elements that are the same.
>
> > > That is:
>
> > >>>> a = [1,1,2,3,4]
> > >>>> b = [4,5,3,7,2,6,1]
> > >>>> set(a).issubset(set(b))
> > > True
>
> > > This will return True if b contains at least on of each element found
> > > in a. If the OP wanted to check that list `a` appeared in order
> > > somewhere in list `b` then sets won't work.
>
> > Indeed, and I should have mentionned this myself. Thanks for this reminder.
>
> If preserving order is important, strings have many of the properties
> you're looking for, but it might take some work to figure out a suitable
> way to convert to a string.  The problem is easier if you know something
> about the inputs.  If all inputs are known to be numbers between 0 and
> 15, you can just do:
>
> if ''.join(map(hex, a)) in ''.join(map(hex, b)):
>     return True
>
> Hmm... actually, with the '0x' prefix that hex() puts on numbers, I
> think this works for arbitrary integers.
>
> Cheers,
> Cliff

Hi,

I looked inside this thread for my query which brought me the
"Test if list contains another list - comp.lang.python | Google
Groups"

But then I was disappointed to see the question asked was not exactly
But what if you actually have to find out if a list has all its
element inside another list in the same order. For that I wrote the
code and that's what I came up with.. let me know if there are any
bugs in this code.

#!C:\Python24

def findAllMatchingList(mainList, subList):
resultIndex = []
globalIndex = 0
for i in range(len(mainList)):
if i < globalIndex:
continue
globalIndex = i
increment = 0
for j in range(len(subList)):
if mainList[globalIndex] == subList[j]:
globalIndex += 1
increment += 1
if j == (len(subList)-1):
resultIndex.append(globalIndex-increment)
else:
break

return resultIndex

if __name__ == "__main__":
#Test case
mL = [ 'a', 'b', 'c', 1, 2, 4, 1, 2, 1, 1, 1, 2, 9, 1, 1, 1, 2, 3,
'a', 1, 2, 3, 4 ];
#mL = [ 'a', 'a', 'b', 1 ,2 ,3, 5, 6]
sL = [ 1, 2, 3 ]
result = findList( mL, sL )
for i in result:
print str(i)

Regards,
Gaurav.

```