How to Count Consecutive Elements in a Python List: 5 Clever Solutions
This article walks through a Python list‑counting problem, presenting five distinct code implementations that compute the length of consecutive identical elements, explains each approach, and provides complete runnable examples with visual output.
Introduction
A follower asked how to count consecutive identical values in a Python list. The original data is shown below.
Solution 1
list1=[1,1,1,0,0,0,1,1,0,1,1,1,1,1,1]
result=[0]
flag=0
for i in range(1,len(list1)):
if list1[i]==list1[i-1]:
flag+=1
else:
flag=0
result.append(flag)
print(result)Solution 2
list1 = [1,1,1,0,0,0,1,1,0,1,1,1,1,1,1]
list2 = []
l = 0
for i in range(len(list1)):
l = l + 1 if list1[i] == list1[i-1] and i != 0 else 0
list2.append(l)
print(list2)Solution 3
list1 = [1,1,1,0,0,0,1,1,0,1,1,1,1,1,1]
result = [0] * len(list1)
result[0] = 0
for i in range(1, len(list1)):
if list1[i] != list1[i-1]:
result[i] = 0
else:
result[i] = result[i-1] + 1
print(result)Solution 4
list1 = [1,1,1,0,0,0,1,1,0,1,1,1,1,1,1]
result = [0] * len(list1)
pre_num = 0
for num in range(len(list1)):
print(num, pre_num)
if list1[num] != list1[pre_num]:
pre_num = num
result[num] = num - pre_num
print(result)
print(result)Solution 5
from functools import reduce
from itertools import groupby
list1 = [1,1,1,0,0,0,1,1,0,1,1,1,1,1,1]
ret = reduce(lambda x, y: x + y, [[i for i in range(len(list(num)))] for item, num in groupby(list1)])
print(ret)Conclusion
The article presents five different Python implementations for counting consecutive identical elements in a list, demonstrating techniques such as flag counters, list comprehensions, pre‑number tracking, and functional tools like reduce and groupby. Each solution includes full source code and a screenshot of its output.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
