def listInList(list1, list2):
???
list1 = [0,0,0,0,1,0,1,0,0,0,1,0,1,0,0]
list2 = [1,0,1]
print(listInList(list1, list2))
How would I go about having the above code return [4, 10]?
def listInList(list1, list2):
???
list1 = [0,0,0,0,1,0,1,0,0,0,1,0,1,0,0]
list2 = [1,0,1]
print(listInList(list1, list2))
How would I go about having the above code return [4, 10]?
Borrowing from this related post (which is not a duplicate because that one is just about seeing if the sublist is contained in the list, not the count or indices of occurrences), I came up with a solution. Code:
list1 = [0,0,0,0,1,0,1,0,0,0,1,0,1,0,0]
list2 = [1,0,1]
def contains_sublist(lst, sublst):
n = len(sublst)
instances = []
for i in range(len(lst)-n+1):
if sublst == lst[i:i+n]:
instances.append(i)
return instances
print(contains_sublist(list1, list2))
Output:
[4, 10]
You just need to loop over the sublists:
def listInList(list1, list2):
return [i for i in range(len(list1)-len(list2)+1)
if list1[i:i+len(list2)]==list2]
list1 = [0,0,0,0,1,0,1,0,0,0,1,0,1,0,0]
list2 = [1,0,1]
print(listInList(list1, list2))
Output; [4, 10]