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
Python – Extract range of Consecutive similar elements ranges from string list
When it is required to extract range of consecutive similar elements ranges from list, a simple iteration and the ‘append’ method is used.
Example
Below is a demonstration of the same −
my_list = [12, 23, 23, 23, 48, 48, 36, 17, 17]
print("The list is : ")
print(my_list)
my_result = []
index = 0
while index Output
The list is :
[12, 23, 23, 23, 48, 48, 36, 17, 17]
The my_result is :
[(12, 0, 0), (23, 1, 3), (48, 4, 5), (36, 6, 6), (17, 7, 8)]
Explanation
A list is defined and displayed on the console.
An empty list is created.
The value for index is defined as 0.
The list is iterated over, and a ‘while’ condition is placed.
This checks to see if the specific index is less than the length of the list and whether the specific value at the index is same as the previously defined values.
If yes, the index is incremented.
Otherwise, the index is decremented by 1 and assigned to another variable.
The integers are appended to the empty list.
This is the output that is displayed on the console.
