testing if a list contains a sublist
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Aug 15 22:12:18 EDT 2011
On Tue, 16 Aug 2011 09:26 am 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)?
This is not the most efficient algorithm, but for short lists it should be
plenty fast enough:
def contains(alist, sublist):
if len(sublist) == 0 or len(sublist) > len(alist):
return False
start = 0
while True:
try:
p = alist.index(sublist[0], start)
except ValueError:
return False
for i,x in enumerate(sublist):
if alist[p+i] != x:
start = p+1
break
else: # for loop exits without break
return True
--
Steven
More information about the Python-list
mailing list