So I was solving a problem that wanted me to find out the number of times a sublist has occurred in a given list.
def count_sublist_occurrence(sublst, lst):
"""
Input : non-empty list (sublst) and list (lst)
Output: the number of times sublst occurs in lst
For example:
>>> count_sublist_occurrence([1, 2], [1, 2, 3, 1, 2, 3])
2
"""
counter = 0
for i in range(len(lst)):
if lst[i : len(sublst) + i] == sublst:
counter += 1
return counter
It is not required to shorten the list but I decided to give it a try anyway. I tried to shorten it with list comprehension and I wrote something like this
counter for i in range(len(lst)) if lst[i : len(sublst) + 1] == sublst #counter += 1
This code is obviously wrong as I don't know how to increment the counter inside a list comprehension.
Is there a way for me to code this?