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

Original List: 12 0 23 1 23 2 23 3 48 4 48 5 36 6 17 7 17 8 Extracted Ranges: (12, 0, 0) ? Value 12 from index 0 to 0 (23, 1, 3) ? Value 23 from index 1 to 3 (48, 4, 5) ? Value 48 from index 4 to 5 (36, 6, 6) ? Value 36 from index 6 to 6 (17, 7, 8) ? Value 17 from index 7 to 8 Algorithm Steps: 1. Start at index 0 2. Find consecutive elements 3. Record start & end positions 4. Store (value, start, end) 5. Move to next different element

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.

Updated on: 2026-03-26T01:26:02+05:30

333 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements