testing if a list contains a sublist

ChasBrown cbrown at cbrownsystems.com
Wed Aug 17 06:13:20 CEST 2011


On Aug 16, 1:37 am, Steven D'Aprano <steve
+comp.lang.pyt... at pearwood.info> wrote:
> On Tue, 16 Aug 2011 04:14 pm ChasBrown wrote:
>
>
>
> > On Aug 15, 4:26 pm, Johannes <dajo.m... at web.de> wrote:
> >> hi list,
> >> what is the best way to check if a given list (lets call it l1) is
> >> totally contained in a second list (l2)?
>
> >> for example:
> >> l1 = [1,2], l2 = [1,2,3,4,5] -> l1 is contained in l2
> >> l1 = [1,2,2,], l2 = [1,2,3,4,5] -> l1 is not contained in l2
> >> l1 = [1,2,3], l2 = [1,3,5,7] -> l1 is not contained in l2
>
> >> my problem is the second example, which makes it impossible to work with
> >> sets insteads of lists. But something like set.issubset for lists would
> >> be nice.
>
> >> greatz Johannes
>
> > My best guess:
>
> > from collections import Counter
>
> There's no reason to think that the Original Poster wants a multiset based
> solution. He asked about lists and sublists. That's a standard term, like
> substring:
>
> "12" is a substring of "01234".
> "21" and "13" are not.
>
> [1, 2] is a sublist of [0, 1, 2, 3, 4].
> [2, 1] and [1, 3] are not.
>
> Since lists are ordered, so are sublists.
>

That's reasonable; although except in the subject, the OP never uses
the term 'sublist'; instead using more ambiguous terms like
'contains', 'is totally contained', etc., with definition by limited
example. So it was a bit of a guess on my part of what was wanted.

> If the OP does want a solution that ignores order, then he needs to describe
> his problem better.

As it turns out, in another response the OP says he wants [2,1,2] to
be 'contained' by [1,2,2]. But in any case he always has sorted lists,
in which case, interestingly, the multiset approach and your more
canonical sublist approach yield the same results.

Cheers - Chas



More information about the Python-list mailing list