user5368737 user5368737 - 5 months ago 14
Python Question

Find number of consecutive elements that are the same before they change

So for example if I have the lists

a = [1,1,1,2,2]
b = [1,1,2,2,2]
c = [2,1,1,1,1]


I would want to get the longest streak of the first element in the list, so for example
a
would give 3,
b
would give 2 and
c
would give 1. I know I could create a while loop and count the streak that way, but I was wondering if there's a more elegant way to do this?

Answer

you could do something like this:

numStreak = ([a[0] == n for n in a]+[False]).index(False)

(this also makes sure that if all elements are like the first element, index does return the correct value)

UPDATE: a more efficient (but less elegant?) version

from itertools import takewhile
len([tmp for tmp in takewhile(lambda x:x==a[0], a)])