Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Consecutive identical elements count
When working with lists in Python, you might need to count how many distinct values appear consecutively (repeated adjacent elements). This can be achieved using iteration, the append() method, and set() to find unique consecutive elements.
Example
Here's how to count distinct consecutive identical elements in a list ?
my_list = [24, 24, 24, 15, 15, 64, 64, 71, 13, 95, 100]
print("The list is :")
print(my_list)
my_result = []
for index in range(0, len(my_list) - 1):
if my_list[index] == my_list[index + 1]:
my_result.append(my_list[index])
my_result = len(list(set(my_result)))
print("The result is :")
print(my_result)
The list is : [24, 24, 24, 15, 15, 64, 64, 71, 13, 95, 100] The result is : 3
How It Works
The algorithm works as follows ?
A list is defined and displayed on the console.
An empty list is created to store consecutive identical elements.
The list is iterated, comparing each element with the next one. If they are equal, the current element is added to the result list.
The result list is converted to a set (removing duplicates) and back to a list, then its length gives the count of distinct consecutive identical elements.
In this example, elements 24, 15, and 64 appear consecutively, so the result is 3.
Alternative Method Using itertools.groupby()
A more elegant approach uses itertools.groupby() to group consecutive identical elements ?
from itertools import groupby
my_list = [24, 24, 24, 15, 15, 64, 64, 71, 13, 95, 100]
print("The list is :")
print(my_list)
consecutive_groups = [list(group) for key, group in groupby(my_list)]
consecutive_identical = [group for group in consecutive_groups if len(group) > 1]
print("Consecutive identical groups:")
print(consecutive_identical)
print("Count of distinct consecutive identical elements:")
print(len(consecutive_identical))
The list is : [24, 24, 24, 15, 15, 64, 64, 71, 13, 95, 100] Consecutive identical groups: [[24, 24, 24], [15, 15], [64, 64]] Count of distinct consecutive identical elements: 3
Conclusion
Both methods effectively count distinct consecutive identical elements. The first approach uses basic iteration and set operations, while itertools.groupby() provides a more readable and efficient solution for grouping consecutive elements.
