Test if list contains another list

Matimus mccredie at gmail.com
Mon Sep 8 12:24:20 EDT 2008


On Sep 8, 12:32 am, Bruno Desthuilliers
<bdesth.quelquech... at free.quelquepart.fr> wrote:
> mathieu a écrit :
>
> > Hi there,
>
> >   I am trying to write something very simple to test if a list
> > contains another one:
>
> > a = [1,2,3]
>
> > b = [3,2,1,4]
>
> > but 'a in b' returns False.
>
> Indeed. Lists are not sets, and the fact that all elements of list a
> happens to also be part of list b doesn't make the list a itself an
> element of list b.
>
>  >>> a = [1, 2, 3]
>  >>> b = [3,2,1,4]
>  >>> c = [b, a]
>  >>> a in c
> True
>  >>> b in c
> True
>  >>> c
> [[3, 2, 1, 4], [1, 2, 3]]
>  >>>
>
> > How do I check that a is indeed contained
> > in b ?
>
> But that's what you did - you *did* checked if a was contained in b, and
> this is not the case. What you want is to check if *all elements* of a
> are contained in b, which is quite another problem. Now the answer to
> your question : use sets.
>
>  >>> set(a).issubset(set(b))
> True
>  >>>
>
> HTH

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.

Matt



More information about the Python-list mailing list