How to compress consecutive numbers into range strings in Python

Convert a sorted list of consecutive integers into compact range strings like '1-3', '5-6', and '15'.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 15 views 0 copies

Python code

29 lines
Python 3.9+
def compress_ranges(nums):
    """Convert a list of sorted consecutive numbers into range strings."""
    if not nums:
        return []
    
    ranges = []
    start = prev = nums[0]
    
    for num in nums[1:]:
        if num == prev + 1:
            prev = num
        else:
            if start == prev:
                ranges.append(str(start))
            else:
                ranges.append(f"{start}-{prev}")
            start = prev = num
    
    # Handle the last range
    if start == prev:
        ranges.append(str(start))
    else:
        ranges.append(f"{start}-{prev}")
    
    return ranges

if __name__ == "__main__":
    numbers = [1, 2, 3, 5, 6, 8, 10, 11, 12, 15]
    print(compress_ranges(numbers))

Output

stdout
['1-3', '5-6', '8', '10-12', '15']

How it works

The function scans the list once, tracking the start of the current run and the previous number. When a number is exactly one greater than the previous, it extends the run; otherwise it finalizes the current run (as a single number or a range) and starts a new one. After the loop, the final run is flushed. This works because the input must be sorted — the check num == prev + 1 depends on consecutive ordering. Time complexity is O(n) and space is O(n) for the output list.

Common mistakes

  • Forgetting to handle the last range after the loop
  • Assuming the input is sorted when it isn't — the code only works on ordered lists
  • Appending `start-prev` even when start equals prev (should be just the number)

Variations

  1. Use a generator with `yield` to produce ranges lazily for very large lists
  2. Use `itertools.groupby` with a key function that subtracts the index from each number to group consecutive runs

Real-world use cases

  • Summarizing which rows in a large dataset have errors by grouping consecutive row numbers.
  • Displaying available IP addresses or port ranges in a network scanning tool.
  • Compressing calendar dates or event IDs into human-readable ranges for log reporting.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.