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'.
Python code
29 linesdef 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
['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
- Use a generator with `yield` to produce ranges lazily for very large lists
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.