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:

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

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
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download