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
Selected Reading
Python – Extract range of Consecutive similar elements ranges from string list
When working with lists containing consecutive similar elements, you often need to extract ranges showing where each group of identical elements starts and ends. Python provides a simple approach using iteration and the append() method to identify these consecutive groups.
Example
Below is a demonstration of extracting consecutive similar element ranges ?
my_list = [12, 23, 23, 23, 48, 48, 36, 17, 17]
print("The list is:")
print(my_list)
my_result = []
index = 0
while index < (len(my_list)):
start_position = index
val = my_list[index]
while (index < len(my_list) and my_list[index] == val):
index += 1
end_position = index - 1
my_result.append((val, start_position, end_position))
print("The result is:")
print(my_result)
Output
The list is: [12, 23, 23, 23, 48, 48, 36, 17, 17] The result is: [(12, 0, 0), (23, 1, 3), (48, 4, 5), (36, 6, 6), (17, 7, 8)]
How It Works
The algorithm works by:
- Outer loop: Iterates through each unique group of consecutive elements
- Inner loop: Finds the end of each consecutive group by comparing adjacent elements
- Tracking: Records the value, start position, and end position for each group
- Result: Returns tuples containing (value, start_index, end_index) for each consecutive group
Alternative Using itertools.groupby()
You can also use itertools.groupby() for a more concise solution ?
import itertools
my_list = [12, 23, 23, 23, 48, 48, 36, 17, 17]
print("The list is:")
print(my_list)
result = []
start_idx = 0
for value, group in itertools.groupby(my_list):
group_list = list(group)
end_idx = start_idx + len(group_list) - 1
result.append((value, start_idx, end_idx))
start_idx = end_idx + 1
print("The result is:")
print(result)
The list is: [12, 23, 23, 23, 48, 48, 36, 17, 17] The result is: [(12, 0, 0), (23, 1, 3), (48, 4, 5), (36, 6, 6), (17, 7, 8)]
Conclusion
Both approaches effectively extract consecutive similar element ranges. The manual iteration method gives more control, while itertools.groupby() provides a cleaner, more Pythonic solution for grouping consecutive identical elements.
Advertisements
