You need to keep track of two variables, the current count
(count) of the consecutive values and the maximum count
(max_count) so far. When you observe a different value, you reset
count and update
max_count and continue the loop.
def get_longest_seq(l, val): count = 0 max_count = 0 for e in l: if e == val: count += 1 elif count > 0: max_count = max(max_count, count) count = 0 max_count = max(max_count, max) # case when the sequence is at the end return max_count l = [2,2,3,2,2,2,2,3,3,4,4,4,5,4,4,7,6] print(get_longest_seq(l, 4))