testing if a list contains a sublist

alex23 wuwei23 at gmail.com
Tue Aug 16 09:19:20 CEST 2011


Laszlo Nagy <gand... at shopzeus.com> wrote:
> Fastest, error-free and simplest solution is to use sets:
>
>  >>> l1 = [1,2]
>  >>> l2 = [1,2,3,4,5]
>  >>> set(l1)-set(l2)
> set([])
>  >>> set(l2)-set(l1)
> set([3, 4, 5])
>  >>>

Error-free? Not given the stated requirements:

> l1 = [1,2,2,], l2 = [1,2,3,4,5] -> l1 is not contained in l2

>>> l1 = [1,2,2]
>>> l2 = [1,2,3,4,5]
>>> set(l1)-set(l2)
set()
>>> set(l2)-set(l1)
{3, 4, 5}

As you can see, using sets provides the exact same result for a non-
contained sub-list as it does for your valid example. The list
[1,2,2,2,2,2,2,2,2] is clearly not contained with [1,2,3], but your
code would say it is.

Similarly, [9,8,7] would appear to be a sub-list of [5,6,7,8,9],
something I'd also considered to be false in this instance.

(My apologies if this is a double-up, the original post hasn't
appeared yet)




More information about the Python-list mailing list