0
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]?

GreenCobalt
  • 169
  • 7
  • Compare slices of `list1` starting at each index with `list2`. – Barmar Nov 24 '21 at 22:38
  • 1
    @porrrwal this is not a duplicate. That post is about a true/false. This post is about getting the indices of all occurrences. – Random Davis Nov 24 '21 at 22:44
  • 1
    Does this answer your question? [Python: Return all Indices of every occurrence of a Sub List within a Main List](https://stackoverflow.com/questions/37758370/python-return-all-indices-of-every-occurrence-of-a-sub-list-within-a-main-list) – Red Nov 24 '21 at 22:52
  • What is the expected output if `list2` is `[0, 1, 0]` – d.b Nov 24 '21 at 23:06
  • I've voted to re-open this question, because it is not a duplicate of the question it was voted to be a duplicate of. – Random Davis Nov 24 '21 at 23:24
  • 1
    @RandomDavis Hello! Addressing your comment *"it is not a duplicate of the question it was voted to be a duplicate of"*, I would like to know how is that. This answer seems to do exactly what this post wants: https://stackoverflow.com/a/37758519/13552470 – Red Nov 25 '21 at 01:27
  • @AnnZen Looks like the duplicate post that I was thinking was actually a different one that people flagged this for, so the duplicate that did win out was actually closer to what this post is asking for. I'm not sure why I thought it was the other post that "won out". Not sure if it's possible for the post another post duplicates to be retroactively changed. – Random Davis Nov 26 '21 at 16:02

2 Answers2

1

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]
Random Davis
  • 6,662
  • 4
  • 14
  • 24
0

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]

mozway
  • 194,879
  • 13
  • 39
  • 75