testing if a list contains a sublist

Ameretat Reith ameretat.reith at gmail.com
Wed Aug 17 10:11:21 EDT 2011

On Se shanbe 25 Mordad 1390 01:26:54 Johannes 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

Hope best answer is found so far. for easy answer, i prefer to use Python 
`==' operator instead of inner loop.

for c in xrange(len(l)-sc+1):
        if l[c:sc+c] == s:
                print ( 'found at {0}'.format(c) )

Since sub-lists memory will be garbage collected, there is no problem in 
memory usage, but in time needed for constructing new slice, there is.
Amir Ghassemi Nasr (Reith)
GPG ID: 371035B4 (
GPG Fingerprint: 18E6 CF11 BE80 F541 DC68  B6AF 9373 DE72 3710 35B4
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 230 bytes
Desc: This is a digitally signed message part.
URL: <http://mail.python.org/pipermail/python-list/attachments/20110817/620f3c31/attachment.sig>

More information about the Python-list mailing list