Search code examples
pythonlistloopsuser-defined-functions

Counting consecutive numbers in a list


I couldn't find a question that was similar enough to mine to where I could develop a satisfactory answer.

I'm pretty new to Python (3.4.3). I am trying to add elements to an output list using a for loop by comparing each element of an input list to the next element in it.

Here is my code so far:

random_list=[1,4,5,6,7,9,19,21,22,23,24]

def count_consec(random_list):
    count=1
    consec_list=[]
    for i in listrand:
        if listrand[i] == listrand[i+1]+1:
            count+=1
        else:
            list.append(count)
    return consec_list

Basically, I want to add to consec_list[] values that represent how the length of consecutive blocks of numbers in random_list[].

I expect my output in this case to look like this:

[1,4,1,1,4]

As in, there is one singular number, followed by 4 consecutive numbers, followed by one singular number, followed by one singular number, followed by 4 consecutive numbers.

I tried many different ways and I have gotten the function to build a list, but all the elements are 1s.


Solution

  • You could take an approach like this:

    def countlist(random_list):
        retlist = []
        # Avoid IndexError for  random_list[i+1]
        for i in range(len(random_list) - 1):
            # Check if the next number is consecutive
            if random_list[i] + 1 == random_list[i+1]:
                count += 1
            else:
                # If it is not append the count and restart counting
                retlist.append(count)
                count = 1
        # Since we stopped the loop one early append the last count
        retlist.append(count)
        return retlist