Test if list contains another list

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Sep 8 03:32:01 EDT 2008


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




More information about the Python-list mailing list