Patrick Abeli Patrick Abeli - 4 years ago 136
Python Question

Counting consecutive numbers in a list

Sorry if this has already been asked; 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 empty list using a for loop by comparing the elements of another list to the next element in that second list (terrible explanation; I apologize).

Here is my code so far:


def count_consec(random_list):
for i in listrand:
if listrand[i] == listrand[i+1]+1:
return consec_list

Basically, I want to add to 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:


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've tried this many different ways, and I have gotten the function to build a list, but all the elements are 1's...

Thanks for your help!

Answer Source

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
            # If it is not append the count and restart counting
            count = 1
    # Since we stopped the loop one early append the last count
    return retlist
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download