5 Ways to Count Consecutive Elements in a Python List
This article walks through a Python list problem where you need to compute the length of consecutive identical elements, presenting five distinct code solutions with explanations, sample inputs, and output visualizations to help readers understand and apply the techniques.
1. Introduction
A follower asked how to process a Python list to count consecutive identical values. The original list is shown below.
2. Implementation
Below are five different implementations submitted by community members.
Method 1 (by 瑜亮老师)
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)Method 2 (by 绅)
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)Method 3 (by 逸)
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)Method 4 (by 月神)
list1 = [1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1]
result = [0] * len(list1) # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
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)Method 5 (by 布达佩斯的永恒)
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)3. Conclusion
The article presents five practical solutions for counting consecutive elements in a Python list, each with its own logic and code snippet. Readers are encouraged to try these methods, share alternative approaches, and continue discussing Python programming topics.
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.
