Python - Merge Range Characters in List

Merging range characters in a list involves combining consecutive numbers into grouped ranges. For example, [1, 2, 3, 6, 7, 8, 10] becomes [[1, 2, 3], [6, 7, 8], [10]]. This technique simplifies data representation and improves memory efficiency when working with sequential data.

Benefits of Merging Range Characters

  • Simplified Data Representation: Merging range characters provides a cleaner and more readable format. Instead of individual sequential elements, grouped ranges offer a concise representation that's easier to understand at a glance.

  • Improved Efficiency: Reducing the overall size of the list results in better memory usage. Smaller lists require less storage space and can lead to faster data processing and manipulation.

  • Enhanced Data Analysis: Grouped ranges facilitate data analysis by providing a clear overview of data distribution. This makes it easier to identify patterns, gaps, or anomalies within the dataset.

  • Streamlined Operations: Working with merged ranges simplifies data manipulation operations like slicing, filtering, and transformations, resulting in more efficient and concise code.

Method 1: Using Iterative Comparison

This approach iterates through the list and compares each element with the previous one to determine if they are consecutive ?

Algorithm

Step 1: Initialize an empty list to store the merged ranges.

Step 2: Iterate through each number in the given list.

Step 3: If the list is empty or the current number isn't consecutive to the last range, start a new range.

Step 4: Otherwise, extend the current range by adding the number.

Step 5: Return the merged list.

Example

def merge_ranges_iterative(numbers):
    merged = []
    for num in numbers:
        if not merged or num != merged[-1][-1] + 1:
            merged.append([num])
        else:
            merged[-1].append(num)
    return merged

numbers = [1, 2, 3, 6, 7, 8, 10]
result = merge_ranges_iterative(numbers)
print(result)
[[1, 2, 3], [6, 7, 8], [10]]

Method 2: Using Recursive Approach

This method uses recursion to build ranges by comparing consecutive elements ?

Algorithm

Step 1: Initialize an empty list to store merged ranges.

Step 2: Define a recursive function that takes the list and start/end indices.

Step 3: Check if we've reached the end of the list and add the current range.

Step 4: Compare consecutive elements and either extend the range or start a new one.

Step 5: Call the function recursively and return the result.

Example

def merge_ranges_recursive(numbers):
    merged = []
    
    def merge_recursive(data, start, end):
        if end == len(data) - 1:
            merged.append(data[start:end+1])
            return
        
        if data[end+1] - data[end] != 1:
            merged.append(data[start:end+1])
            merge_recursive(data, end+1, end+1)
        else:
            merge_recursive(data, start, end+1)
    
    if numbers:
        merge_recursive(numbers, 0, 0)
    return merged

numbers = [1, 2, 3, 6, 7, 8, 10]
result = merge_ranges_recursive(numbers)
print(result)
[[1, 2, 3], [6, 7, 8], [10]]

Method 3: Using Range Construction

This approach constructs ranges by tracking start and end points of consecutive sequences ?

Algorithm

Step 1: Sort the input list in ascending order.

Step 2: Initialize variables to track the start and end of each range.

Step 3: Iterate through the list, extending ranges for consecutive numbers.

Step 4: When a gap is found, save the current range and start a new one.

Step 5: Add the final range and return the result.

Example

def merge_ranges_consecutive(numbers):
    if not numbers:
        return []
    
    numbers.sort()
    merged = []
    start = end = numbers[0]
    
    for num in numbers[1:]:
        if num == end + 1:
            end = num
        else:
            merged.append(list(range(start, end+1)))
            start = end = num
    
    merged.append(list(range(start, end+1)))
    return merged

numbers = [1, 2, 3, 6, 7, 8, 10]
result = merge_ranges_consecutive(numbers)
print(result)
[[1, 2, 3], [6, 7, 8], [10]]

Comparison

Method Time Complexity Space Complexity Best For
Iterative O(n) O(n) Simple implementation
Recursive O(n) O(n) Educational purposes
Range Construction O(n log n) O(n) Unsorted input data

Conclusion

Merging range characters in lists is useful for data compression and analysis. The iterative approach is most practical for sorted data, while the range construction method works well with unsorted input. Choose the method that best fits your specific use case and performance requirements.

---
Updated on: 2026-03-27T11:17:05+05:30

320 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements