In Python, how can I increment a count conditionallly?
Question: Say I have the list:

    
    
    list = [a,a,b,b,b]
    

I'm looping over the list. The variable "count" increments by 1 when the
previous letter is the same as the current letter. Below is only part of the
code:

    
    
    for item in list:
        if item == previous:
            count +=1
    return count
    

The example above returns 3, 1 for the repeat a and 2 for the bs. What can I
use to make it so count only increases once for each for a total of 2? I tried
using a variable "found" that returns True or False depending on whether the
letter has been seen before, but this of course doesn't work for something
like [a,a,a,c,a,a,a], which returns 1 for the first run of "a"s and not 2, as
I want.

Edit: I'm probably making this harder than it needs to be. All I want is for
anytime a string is repeated continuously for a count to be incremented by
one. [a,b,b,c,a,a,a,a,c,c,c,] should return 3. [a,a,a,a,a,a,a,a] should return
1.


Answer: Wild guess: since you want `a,a,b,b,b` to be 2 and not 3, and you also want
`a,a,a,c,a,a,a` to give two, I think you're trying to count distinct
contiguous groups of equal elements of length >= 2. If so, you can use
`itertools.groupby`:

    
    
    >>> import itertools
    >>> seq1 = ['a','a','b','b','b']
    >>> [(k, list(g)) for k,g in itertools.groupby(seq1)]
    [('a', ['a', 'a']), ('b', ['b', 'b', 'b'])]
    >>> seq2 = ['a','a','a','c','a','a','a']
    >>> [(k, list(g)) for k,g in itertools.groupby(seq2)]
    [('a', ['a', 'a', 'a']), ('c', ['c']), ('a', ['a', 'a', 'a'])]
    

and thus

    
    
    >>> sum(len(list(g)) >= 2 for k,g in itertools.groupby(seq1))
    2
    >>> sum(len(list(g)) >= 2 for k,g in itertools.groupby(seq2))
    2
    

but this is just a guess. It's the only thing I can think of which matches the
only two data points you've given, at least assuming that I'm interpreting "1
for the first run of "a"s and not 2, as I want" correctly. That leaves it
unclear whether you want the total to be 2 or the contribution from the first
run of "a" to be 2.

