![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Consecutive identical elements count
When it is required to get the count of consecutive identical elements in a list, an iteration, the ‘append’ method, and the ‘set’ method are used.
Example
Below is a demonstration of the same
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)
Output
The list is : [24, 24, 24, 15, 15, 64, 64, 71, 13, 95, 100] The result is : 3
Explanation
A list is defined and is displayed on the console.
An empty list is defined.
The list is iterated over and if the element in the zeroth index and element in the first index are equivalent, the zeroth element is appended to the empty list.
This is converted to a set and then to a list, and its length is assigned to a variable.
This is the output that is displayed on the console.
Advertisements